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()
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
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
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_maxPolygonVertices.
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.
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
Sensor events are buffered in the Box2D 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
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.
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.
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, typically 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 force,
use a force 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, typically 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, typically 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, typically 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 update 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.
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), typically in N*m.
@param wake also wake up the body
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.
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 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::angle
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
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.
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.
@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 ray
@param context user context that is passed to the callback
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
Shift the world origin. Useful for large worlds.
The shift formula is: position -= newOrigin
@param tree the tree to shift
@param newOrigin the new origin with respect to the old origin
Make an offset box, bypassing the need for a convex hull.
@param hx the half-width
@param hy the half-height
@param center the local position of the 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 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 hx the half-width
@param hy the half-height
@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.
@warning This must be modified before any calls to Box2D
Compute the closest points between two shapes represented as point clouds.
b2DistanceCache cache is input/output. On the first call set b2DistanceCache.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.
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
Set the mass density of a shape, typically in kg/m^2.
This will not update the mass properties on the parent body.
@see b2ShapeDef::density, b2Body_ApplyMassFromShapes
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.
The ray-cast ignores shapes that contain the starting point.
@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
@note The callback function may receive shapes in any order
Cast a ray into the world to collect the closest hit. This is a convenience function.
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
Apply a radial explosion
@param worldId The world id
@param position The center of the explosion
@param radius The radius of the explosion
@param impulse The impulse of the explosion, typically in kg * m / s or N * s.
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 pushVelocity The maximum contact constraint push out velocity (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. Typically in m/s^2.
@see b2WorldDef
Adjust the hit event threshold. This controls the collision velocity needed to generate a b2ContactHitEvent.
Typically 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. Typically 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. Typically 1/60.
@param subStepCount The number of sub-steps, increasing the sub-step count can increase accuracy. Typically 4.
Prototype callback for ray 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
@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
@param fraction the fraction along the ray at the point of intersection
@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. @see b2ShapeDef.
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
Prototype callback for overlap queries.
Called for each shape found in the query.
@see b2World_QueryAABB
@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:
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: