A body definition holds all the data needed to construct a rigid body.
You can safely re-use body definitions. Shapes are added to a body after construction.
Body definitions are temporary objects used to bundle creation parameters.
Must be initialized using b2DefaultBodyDef().
@ingroup body
Body events are buffered in the Box2D world and are available
as event arrays after the time step is complete.
Note: this data becomes invalid if bodies are destroyed
Body move events triggered when a body moves.
Triggered when a body moves due to simulation. Not reported for bodies moved by the user.
This also has a flag to indicate that the body went to sleep so the application can also
sleep that actor/entity/object associated with the body.
On the other hand if the flag does not indicate the body went to sleep then the application
can treat the actor/entity/object associated with the body as awake.
This is an efficient way for an application to update game object transforms rather than
calling functions such as b2Body_GetTransform() because this data is delivered as a contiguous array
and it is only populated with bodies that have moved.
@note If sleeping is disabled all dynamic and kinematic bodies will trigger move events.
A line segment with one-sided collision. Only collides on the right side.
Several of these are generated for a chain shape.
ghost1 -> point1 -> point2 -> ghost2
The contact data for two shapes. By convention the manifold normal points
from shape A to shape B.
@see b2Shape_GetContactData() and b2Body_GetContactData()
An end touch event is generated when two shapes stop touching.
You will get an end event if you do anything that destroys contacts previous to the last
world step. These include things like setting the transform, destroying a body
or shape, or changing a filter or body type.
Contact events are buffered in the Box2D world and are available
as event arrays after the time step is complete.
Note: these may become invalid if bodies and/or shapes are destroyed
A hit touch event is generated when two shapes collide with a speed faster than the hit speed threshold.
This may be reported for speculative contacts that have a confirmed impulse.
This is used to filter collision on shapes. It affects shape-vs-shape collision
and shape-versus-query collision (such as b2World_CastRay).
@ingroup shape
Joint events report joints that are awake and have a force and/or torque exceeding the threshold
The observed forces and torques are not returned for efficiency reasons.
Joint events are buffered in the world and are available
as event arrays after the time step is complete.
Note: this data becomes invalid if joints are destroyed
A contact manifold describes the contact points between colliding shapes.
@note Box2D uses speculative collision so some contact points may be separated.
A manifold point is a contact point belonging to a contact manifold.
It holds details related to the geometry and dynamics of the contact points.
Box2D uses speculative collision so some contact points may be separated.
You may use the totalNormalImpulse to determine if there was an interaction during
the time step.
A motor joint is used to control the relative velocity and or transform between two bodies.
With a velocity of zero this acts like top-down friction.
@ingroup motor_joint
A solid convex polygon. It is assumed that the interior of the polygon is to
the left of each edge.
Polygons have a maximum number of vertices equal to B2_MAX_POLYGON_VERTICES.
In most cases you should not need many vertices for a convex polygon.
@warning DO NOT fill this out manually, instead use a helper function like
b2MakePolygon or b2MakeBox.
Prismatic joint definition
Body B may slide along the x-axis in local frame A. Body B cannot rotate relative to body A.
The joint translation is zero when the local frame origins coincide in world space.
@ingroup prismatic_joint
The query filter is used to filter collisions between queries and shapes. For example,
you may want a ray-cast representing a projectile to hit players and the static environment
but not debris.
@ingroup shape
Result from b2World_RayCastClosest
If there is initial overlap the fraction and normal will be zero while the point is an arbitrary point in the overlap region.
@ingroup world
An end touch event is generated when a shape stops overlapping a sensor shape.
These include things like setting the transform, destroying a body or shape, or changing
a filter. You will also get an end event if the sensor or visitor are destroyed.
Therefore you should always confirm the shape id is valid using b2Shape_IsValid.
Sensor events are buffered in the world and are available
as begin/end overlap event arrays after the time step is complete.
Note: these may become invalid if bodies and/or shapes are destroyed
Low level shape cast input in generic form. This allows casting an arbitrary point
cloud wrap with a radius. For example, a circle is a single point with a non-zero radius.
A capsule is two points with a non-zero radius. A box is four points with a zero radius.
Used to create a shape.
This is a temporary object used to bundle shape creation parameters. You may use
the same shape definition to create multiple shapes.
Must be initialized using b2DefaultShapeDef().
@ingroup shape
Used to warm start the GJK simplex. If you call this function multiple times with nearby
transforms this might improve performance. Otherwise you can zero initialize this.
The distance cache must be initialized to zero on the first call.
Users should generally just zero initialize this structure for each call.
This describes the motion of a body/shape for TOI computation. Shapes are defined with respect to the body origin,
which may not coincide with the center of mass. However, to support dynamics we must interpolate the center of mass
position.
Weld joint definition
Connects two bodies together rigidly. This constraint provides springs to mimic
soft-body simulation.
@note The approximate solver in Box2D cannot hold many bodies together rigidly
@ingroup weld_joint
Wheel joint definition
Body B is a wheel that may rotate freely and slide along the local x-axis in frame A.
The joint translation is zero when the local frame origins coincide in world space.
@ingroup wheel_joint
Compute an approximate arctangent in the range [-pi, pi]
This is hand coded for cross-platform determinism. The atan2f
function in the standard library is not cross-platform deterministic.
Accurate to around 0.0023 degrees
Apply an angular impulse. The impulse is ignored if the body is not awake.
This optionally wakes the body.
@param bodyId The body id
@param impulse the angular impulse, usually in units of kgmm/s
@param wake also wake up the body
@warning This should be used for one-shot impulses. If you need a steady torque,
use a torque instead, which will work better with the sub-stepping solver.
Apply a force at a world point. If the force is not applied at the center of mass,
it will generate a torque and affect the angular velocity. This optionally wakes up the body.
The force is ignored if the body is not awake.
@param bodyId The body id
@param force The world force vector, usually in newtons (N)
@param point The world position of the point of application
@param wake Option to wake up the body
Apply a force to the center of mass. This optionally wakes up the body.
The force is ignored if the body is not awake.
@param bodyId The body id
@param force the world force vector, usually in newtons (N).
@param wake also wake up the body
Apply an impulse at a point. This immediately modifies the velocity.
It also modifies the angular velocity if the point of application
is not at the center of mass. This optionally wakes the body.
The impulse is ignored if the body is not awake.
@param bodyId The body id
@param impulse the world impulse vector, usually in Ns or kgm/s.
@param point the world position of the point of application.
@param wake also wake up the body
@warning This should be used for one-shot impulses. If you need a steady force,
use a force instead, which will work better with the sub-stepping solver.
Apply an impulse to the center of mass. This immediately modifies the velocity.
The impulse is ignored if the body is not awake. This optionally wakes the body.
@param bodyId The body id
@param impulse the world impulse vector, usually in Ns or kgm/s.
@param wake also wake up the body
@warning This should be used for one-shot impulses. If you need a steady force,
use a force instead, which will work better with the sub-stepping solver.
This updates the mass properties to the sum of the mass properties of the shapes.
This normally does not need to be called unless you called SetMassData to override
the mass and you later want to reset the mass.
You may also use this when automatic mass computation has been disabled.
You should call this regardless of body type.
Note that sensor shapes may have mass.
Apply a torque. This affects the angular velocity without affecting the linear velocity.
This optionally wakes the body. The torque is ignored if the body is not awake.
@param bodyId The body id
@param torque about the z-axis (out of the screen), usually in N*m.
@param wake also wake up the body
Clear the force and torque on this body. Forces and torques are automatically cleared after each world
step. So this only needs to be called if the application wants to remove the effect of previous
calls to apply forces and torques before the world step is called.
@param bodyId The body id
Get the current world AABB that contains all the attached shapes. Note that this may not encompass the body origin.
If there are no shapes attached then the returned AABB is empty and centered on the body origin.
Enable/disable contact events on all shapes.
@see b2ShapeDef::enableContactEvents
@warning changing this at runtime may cause mismatched begin/end touch events
Get the touching contact data for a body.
@note Box2D uses speculative collision so some contact points may be separated.
@returns the number of elements filled in the provided array
@warning do not ignore the return value, it specifies the valid number of elements
Body identifier validation. A valid body exists in a world and is non-null.
This can be used to detect orphaned ids. Provides validation for up to 64K allocations.
Wake a body from sleep. This wakes the entire island the body is touching.
@warning Putting a body to sleep will put the entire island of bodies touching this body to sleep,
which can be expensive and possibly unintuitive.
Override the body’s mass properties. Normally this is computed automatically using the
shape geometry and density. This information is lost if a shape is added or removed or if the
body type changes.
Set the velocity to reach the given transform after a given time step.
The result will be close but maybe not exact. This is meant for kinematic bodies.
The target is not applied if the velocity would be below the sleep threshold and
the body is currently asleep.
@param bodyId The body id
@param target The target transform for the body
@param timeStep The time step of the next call to b2World_Step
@param wake Option to wake the body or not
Set the world transform of a body. This acts as a teleport and is fairly expensive.
@note Generally you should create a body with then intended transform.
@see b2BodyDef::position and b2BodyDef::rotation
Create a rigid body given a definition. No reference to the definition is retained. So you can create the definition
on the stack and pass it as a pointer.
@code{.c}
b2BodyDef bodyDef = b2DefaultBodyDef();
b2BodyId myBodyId = b2CreateBody(myWorldId, &bodyDef);
@endcode
@warning This function is locked during callbacks.
Create a capsule shape and attach it to a body. The shape definition and geometry are fully cloned.
Contacts are not created until the next time step.
@return the shape id for accessing the shape, this will be b2_nullShapeId if the length is too small.
Create a circle shape and attach it to a body. The shape definition and geometry are fully cloned.
Contacts are not created until the next time step.
@return the shape id for accessing the shape
Create a polygon shape and attach it to a body. The shape definition and geometry are fully cloned.
Contacts are not created until the next time step.
@return the shape id for accessing the shape
Create a line segment shape and attach it to a body. The shape definition and geometry are fully cloned.
Contacts are not created until the next time step.
@return the shape id for accessing the shape
Create a world for rigid body simulation. A world contains bodies, shapes, and constraints. You make create
up to 128 worlds. Each world is completely independent and may be simulated in parallel.
@return the world id.
Destroy a rigid body given an id. This destroys all shapes and joints attached to the body.
Do not keep references to the associated shapes and joints.
Destroy a shape. You may defer the body mass update which can improve performance if several shapes on a
body are destroyed at once.
@see b2Body_ApplyMassFromShapes
Query an AABB for overlapping proxies. The callback class is called for each proxy that overlaps the supplied AABB.
No filtering is performed.
@return performance data
Ray cast against the proxies in the tree. This relies on the callback
to perform a exact ray cast in the case were the proxy contains a shape.
The callback also performs the any collision filtering. This has performance
roughly equal to k * log(n), where k is the number of collisions and n is the
number of proxies in the tree.
Bit-wise filtering using mask bits can greatly improve performance in some scenarios.
However, this filtering may be approximate, so the user should still apply filtering to results.
@param tree the dynamic tree to ray cast
@param input the ray cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1)
@param maskBits mask bit hint: bool accept = (maskBits & node->categoryBits) != 0;
@param callback a callback class that is called for each proxy that is hit by the ray
@param context user context that is passed to the callback
@return performance data
Ray cast against the proxies in the tree. This relies on the callback
to perform a exact ray cast in the case were the proxy contains a shape.
The callback also performs the any collision filtering. This has performance
roughly equal to k * log(n), where k is the number of collisions and n is the
number of proxies in the tree.
@param tree the dynamic tree to ray cast
@param input the ray cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
@param maskBits filter bits: bool accept = (maskBits & node->categoryBits) != 0;
@param callback a callback class that is called for each proxy that is hit by the shape
@param context user context that is passed to the callback
@return performance data
Set the joint constraint tuning. Advanced feature.
@param jointId the joint
@param hertz the stiffness in Hertz (cycles per second)
@param dampingRatio the non-dimensional damping ratio (one for critical damping)
Make a box (rectangle) polygon, bypassing the need for a convex hull.
@param halfWidth the half-width (x-axis)
@param halfHeight the half-height (y-axis)
Make an offset box, bypassing the need for a convex hull.
@param halfWidth the half-width (x-axis)
@param halfHeight the half-height (y-axis)
@param center the local center of the box
@param rotation the local rotation of the box
Make an offset convex polygon from a convex hull. This will assert if the hull is not valid.
@warning Do not manually fill in the hull data, it must come directly from b2ComputeHull
Make an offset rounded box, bypassing the need for a convex hull.
@param halfWidth the half-width (x-axis)
@param halfHeight the half-height (y-axis)
@param center the local center of the box
@param rotation the local rotation of the box
@param radius the radius of the rounded extension
Make an offset convex polygon from a convex hull. This will assert if the hull is not valid.
@warning Do not manually fill in the hull data, it must come directly from b2ComputeHull
Make a convex polygon from a convex hull. This will assert if the hull is not valid.
@warning Do not manually fill in the hull data, it must come directly from b2ComputeHull
Make a rounded box, bypassing the need for a convex hull.
@param halfWidth the half-width (x-axis)
@param halfHeight the half-height (y-axis)
@param radius the radius of the rounded extension
Set the prismatic joint stiffness in Hertz.
This should usually be less than a quarter of the simulation rate. For example, if the simulation
runs at 60Hz then the joint stiffness should be 15Hz or less.
Box2D bases all length units on meters, but you may need different units for your game.
You can set this value to use different units. This should be done at application startup
and only modified once. Default value is 1.
For example, if your game uses pixels for units you can use pixels for all length values
sent to Box2D. There should be no extra cost. However, Box2D has some internal tolerances
and thresholds that have been tuned for meters. By calling this function, Box2D is able
to adjust those tolerances and thresholds to improve accuracy.
A good rule of thumb is to pass the height of your player character to this function. So
if your player character is 32 pixels high, then pass 32 to this function. Then you may
confidently use pixels for all the length values sent to Box2D. All length values returned
from Box2D will also be pixels because Box2D does not do any scaling internally.
However, you are now on the hook for coming up with good values for gravity, density, and
forces.
@warning This must be modified before any calls to Box2D
Perform a linear shape cast of shape B moving and shape A fixed. Determines the hit point, normal, and translation fraction.
Initially touching shapes are treated as a miss.
Compute the closest points between two shapes represented as point clouds.
b2SimplexCache cache is input/output. On the first call set b2SimplexCache.count to zero.
The underlying GJK algorithm may be debugged by passing in debug simplexes and capacity. You may pass in NULL and 0 for these.
Apply a wind force to the body for this shape using the density of air. This considers
the projected area of the shape in the wind direction. This also considers
the relative velocity of the shape.
@param shapeId the shape id
@param wind the wind velocity in world space
@param drag the drag coefficient, the force that opposes the relative velocity
@param lift the lift coefficient, the force that is perpendicular to the relative velocity
@param wake should this wake the body
Enable contact events for this shape. Only applies to kinematic and dynamic bodies. Ignored for sensors.
@see b2ShapeDef::enableContactEvents
@warning changing this at run-time may lead to lost begin/end events
Enable pre-solve contact events for this shape. Only applies to dynamic bodies. These are expensive
and must be carefully handled due to multithreading. Ignored for sensors.
@see b2PreSolveFcn
Get the touching contact data for a shape. The provided shapeId will be either shapeIdA or shapeIdB on the contact data.
@note Box2D uses speculative collision so some contact points may be separated.
@returns the number of elements filled in the provided array
@warning do not ignore the return value, it specifies the valid number of elements
Get the maximum capacity required for retrieving all the overlapped shapes on a sensor shape.
This returns 0 if the provided shape is not a sensor.
@param shapeId the id of a sensor shape
@returns the required capacity to get all the overlaps in b2Shape_GetSensorOverlaps
Get the overlap data for a sensor shape.
@param shapeId the id of a sensor shape
@param visitorIds a user allocated array that is filled with the overlapping shapes (visitors)
@param capacity the capacity of overlappedShapes
@returns the number of elements filled in the provided array
@warning do not ignore the return value, it specifies the valid number of elements
@warning overlaps may contain destroyed shapes so use b2Shape_IsValid to confirm each overlap
Returns true if the shape is a sensor. It is not possible to change a shape
from sensor to solid dynamically because this breaks the contract for
sensor events.
Set the mass density of a shape, usually in kg/m^2.
This will optionally update the mass properties on the parent body.
@see b2ShapeDef::density, b2Body_ApplyMassFromShapes
Set the current filter. This is almost as expensive as recreating the shape. This may cause
contacts to be immediately destroyed. However contacts are not created until the next world step.
Sensor overlap state is also not updated until the next world step.
@see b2ShapeDef::filter
Solves the position of a mover that satisfies the given collision planes.
@param targetDelta the desired movement from the position used to generate the collision planes
@param planes the collision planes
@param count the number of collision planes
Compute the upper bound on time before two shapes penetrate. Time is represented as
a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate,
non-tunneling collisions. If you change the time interval, you should call this function
again.
Cast a ray into the world to collect shapes in the path of the ray.
Your callback function controls whether you get the closest point, any point, or n-points.
@note The callback function may receive shapes in any order
@param worldId The world to cast the ray against
@param origin The start point of the ray
@param translation The translation of the ray from the start point to the end point
@param filter Contains bit flags to filter unwanted shapes from the results
@param fcn A user implemented callback function
@param context A user context that is passed along to the callback function
@return traversal performance counters
Cast a ray into the world to collect the closest hit. This is a convenience function. Ignores initial overlap.
This is less general than b2World_CastRay() and does not allow for custom filtering.
Enable/disable continuous collision between dynamic and static bodies. Generally you should keep continuous
collision enabled to prevent fast moving objects from going through static objects. The performance gain from
disabling continuous collision is minor.
@see b2WorldDef
Enable/disable sleep. If your application does not need sleeping, you can gain some performance
by disabling sleep completely at the world level.
@see b2WorldDef
Adjust contact tuning parameters
@param worldId The world id
@param hertz The contact stiffness (cycles per second)
@param dampingRatio The contact bounciness with 1 being critical damping (non-dimensional)
@param pushSpeed The maximum contact constraint push out speed (meters per second)
@note Advanced feature
Set the gravity vector for the entire world. Box2D has no concept of an up direction and this
is left as a decision for the application. Usually in m/s^2.
@see b2WorldDef
Adjust the hit event threshold. This controls the collision speed needed to generate a b2ContactHitEvent.
Usually in meters per second.
@see b2WorldDef::hitEventThreshold
Adjust the restitution threshold. It is recommended not to make this value very small
because it will prevent bodies from sleeping. Usually in meters per second.
@see b2WorldDef
Simulate a world for one time step. This performs collision detection, integration, and constraint solution.
@param worldId The world to simulate
@param timeStep The amount of time to simulate, this should be a fixed number. Usually 1/60.
@param subStepCount The number of sub-steps, increasing the sub-step count can increase accuracy. Usually 4.
Prototype callback for ray and shape casts.
Called for each shape found in the query. You control how the ray cast
proceeds by returning a float:
return -1: ignore this shape and continue
return 0: terminate the ray cast
return fraction: clip the ray to this point
return 1: don’t clip the ray and continue
A cast with initial overlap will return a zero fraction and a zero normal.
@param shapeId the shape hit by the ray
@param point the point of initial intersection
@param normal the normal vector at the point of intersection, zero for a shape cast with initial overlap
@param fraction the fraction along the ray at the point of intersection, zero for a shape cast with initial overlap
@param context the user context
@return -1 to filter, 0 to terminate, fraction to clip the ray for closest hit, 1 to continue
@see b2World_CastRay
@ingroup world
Prototype for a contact filter callback.
This is called when a contact pair is considered for collision. This allows you to
perform custom logic to prevent collision between shapes. This is only called if
one of the two shapes has custom filtering enabled.
Notes:
These functions can be provided to Box2D to invoke a task system. These are designed to work well with enkiTS.
Returns a pointer to the user’s task object. May be nullptr. A nullptr indicates to Box2D that the work was executed
serially within the callback and there is no need to call b2FinishTaskCallback.
The itemCount is the number of Box2D work items that are to be partitioned among workers by the user’s task system.
This is essentially a parallel-for. The minRange parameter is a suggestion of the minimum number of items to assign
per worker to reduce overhead. For example, suppose the task is small and that itemCount is 16. A minRange of 8 suggests
that your task system should split the work items among just two workers, even if you have more available.
In general the range [startIndex, endIndex) send to b2TaskCallback should obey:
endIndex - startIndex >= minRange
The exception of course is when itemCount < minRange.
@ingroup world
Optional friction mixing callback. This intentionally provides no context objects because this is called
from a worker thread.
@warning This function should not attempt to modify Box2D state or user application state.
@ingroup world
These colors are used for debug draw and mostly match the named SVG colors.
See https://www.rapidtables.com/web/color/index.html
https://johndecember.com/html/spec/colorsvg.html
https://upload.wikimedia.org/wikipedia/commons/2/2b/SVG_Recognized_color_keyword_names.svg
Prototype callback for overlap queries.
Called for each shape found in the query.
@see b2World_OverlapABB
@return false to terminate the query.
@ingroup world
Prototype for a pre-solve callback.
This is called after a contact is updated. This allows you to inspect a
contact before it goes to the solver. If you are careful, you can modify the
contact manifold (e.g. modify the normal).
Notes:
Optional restitution mixing callback. This intentionally provides no context objects because this is called
from a worker thread.
@warning This function should not attempt to modify Box2D state or user application state.
@ingroup world
Task interface
This is prototype for a Box2D task. Your task system is expected to invoke the Box2D task with these arguments.
The task spans a range of the parallel-for: [startIndex, endIndex)
The worker index must correctly identify each worker in the user thread pool, expected in [0, workerCount).
A worker must only exist on only one thread at a time and is analogous to the thread index.
The task context is the context pointer sent from Box2D when it is enqueued.
The startIndex and endIndex are expected in the range [0, itemCount) where itemCount is the argument to b2EnqueueTaskCallback
below. Box2D expects startIndex < endIndex and will execute a loop like this: