Phaser Box2D

v1.1.0

Jump to: Aabb ‐ Body ‐ Core ‐ DebugDraw ‐ Distance ‐ DistanceJoint ‐ DynamicTree ‐ Geometry ‐ Hull ‐ Joint ‐ Manifold ‐ MathFunctions ‐ MotorJoint ‐ MouseJoint ‐ PrismaticJoint ‐ RevoluteJoint ‐ Shape ‐ Types ‐ WeldJoint ‐ WheelJoint ‐ World ‐ Base ‐ Collision ‐ Id ‐ Helpers ‐

Aabb

Aabb

Aabb

Body

Body

Body

b2CreateBody

Creates a new physics body in the specified world based on the provided body definition. The body is added to the appropriate solver set based on its type and state. The function initializes the body's physical properties including position, rotation, velocities, damping values and other simulation parameters.

b2CreateBody(worldId: b2WorldId, def: b2BodyDef): b2BodyId
Parameters
worldId (b2WorldId) The ID of the world to create the body in
def (b2BodyDef) The body definition containing initialization parameters
Returns
b2BodyId: The ID of the newly created body
Throws
  • Error: Throws assertion errors if:
    • Position vector is invalid
    • Rotation value is invalid
    • Linear velocity vector is invalid
    • Angular velocity is invalid
    • Linear damping is invalid or negative
    • Angular damping is invalid or negative
    • Sleep threshold is invalid or negative
    • Gravity scale is invalid

b2DestroyBody

Destroys a body and all associated joints, contacts, shapes, and chains in the physics world. The function cleans up all resources and removes the body from the simulation system.

b2DestroyBody(bodyId: b2BodyId): void
Parameters
bodyId (b2BodyId) The identifier of the body to destroy
Returns
void:
Throws
  • Error: Throws assertion errors if body indices are invalid during removal

b2Body_GetContactCapacity

Retrieves the current number of contacts associated with the specified body. The function first validates the world reference before accessing the body's contact count.

b2Body_GetContactCapacity(bodyId: b2BodyId): number
Parameters
bodyId (b2BodyId) The identifier for the body to query
Returns
number: The number of contacts associated with the body. Returns 0 if the world is invalid.

b2Body_GetContactData

Retrieves contact data for a specified body. For each active contact, stores the shape IDs of both bodies involved and the contact manifold. Only stores contacts that have the touching flag set.

b2Body_GetContactData(bodyId: b2BodyId, contactData: Array<b2ContactData>, capacity: number): number
Parameters
bodyId (b2BodyId) The ID of the body to get contact data from
contactData (Array<b2ContactData>) Array to store the contact data
capacity (number) Maximum number of contacts to retrieve
Returns
number: The number of contacts stored in contactData
Throws
  • Error: If the world is locked or invalid

b2Body_ComputeAABB

For bodies with no shapes, returns an AABB containing only the body's position. For bodies with shapes, computes the union of AABBs of all shapes attached to the body.

b2Body_ComputeAABB(bodyId: b2BodyId): b2AABB
Parameters
bodyId (b2BodyId) The identifier for the body whose AABB is to be computed.
Returns
b2AABB: An AABB that encompasses the body and all its shapes. Returns an empty AABB if the world is not found.

b2Body_GetPosition

Retrieves the current position component of a body's transform from the physics world. The position is returned as a b2Vec2 representing the body's location in world space.

b2Body_GetPosition(bodyId: b2BodyId): b2Vec2
Parameters
bodyId (b2BodyId) The identifier for the body whose position is being queried.
Returns
b2Vec2: The position vector of the body in world coordinates.

b2Body_GetRotation

Retrieves the rotation component (q) from the body's transform. The returned b2Rot object represents the body's angular orientation in 2D space.

b2Body_GetRotation(bodyId: b2BodyId): b2Rot
Parameters
bodyId (b2BodyId) The identifier for the body whose rotation is being queried.
Returns
b2Rot: A rotation object containing the cosine and sine of the body's angle.

b2Body_GetTransform

Retrieves the current transform (position and rotation) of a physics body from the specified Box2D world using the body's identifier.

b2Body_GetTransform(bodyId: Object): Object
Parameters
bodyId (Object) The identifier object for the body, containing world reference.
Name Description
bodyId.world0 number The world identifier.
Returns
Object: The body's transform containing:
  • position {b2Vec2} The position vector (x, y)
  • rotation {b2Rot} The rotation values (c, s)

b2Body_GetLocalPoint

Takes a point given in world coordinates and converts it to the body's local coordinate system by applying the inverse of the body's transform.

b2Body_GetLocalPoint(bodyId: b2BodyId, worldPoint: b2Vec2): b2Vec2
Parameters
bodyId (b2BodyId) The identifier for the body
worldPoint (b2Vec2) A point in world coordinates
Returns
b2Vec2: The point expressed in the body's local coordinates

b2Body_GetWorldPoint

Takes a point given in body-local coordinates and converts it to world coordinates using the body's current transform (position and rotation).

b2Body_GetWorldPoint(bodyId: b2BodyId, localPoint: b2Vec2): b2Vec2
Parameters
bodyId (b2BodyId) The identifier for the body.
localPoint (b2Vec2) A point in the body's local coordinates.
Returns
b2Vec2: The point transformed to world coordinates.

b2Body_GetLocalVector

Takes a vector defined in world coordinates and transforms it to be relative to the body's local coordinate system by applying the inverse of the body's rotation.

b2Body_GetLocalVector(bodyId: b2BodyId, worldVector: b2Vec2): b2Vec2
Parameters
bodyId (b2BodyId) The identifier for the body
worldVector (b2Vec2) A vector in world coordinates
Returns
b2Vec2: The vector transformed into the body's local coordinates

b2Body_GetWorldVector

Transforms a vector from the body's local coordinate system to the world coordinate system. This operation only performs rotation (not translation) using the body's current rotation matrix.

b2Body_GetWorldVector(bodyId: b2BodyId, localVector: b2Vec2): b2Vec2
Parameters
bodyId (b2BodyId) The identifier for the body
localVector (b2Vec2) A vector in local body coordinates
Returns
b2Vec2: The vector transformed into world coordinates

b2Body_SetTransform

Sets the position and rotation of a body, updating its transform and associated shape AABBs. The function updates the body's center, handles broad-phase movement, and adjusts collision bounds.

b2Body_SetTransform(bodyId: b2BodyId, position: b2Vec2, rotation: b2Rot?): void
Parameters
bodyId (b2BodyId) The identifier of the body to transform
position (b2Vec2) The new position vector for the body
rotation (b2Rot?) The new rotation for the body. If undefined, keeps current rotation
Returns
void:
Throws
  • Error: Throws assertion error if:
    • The position vector is invalid
    • The body ID is invalid
    • The world is locked
    • The rotation (if provided) is invalid

b2Body_GetLinearVelocity

Retrieves the current linear velocity of a body from its state in the physics world. If the body state cannot be found, returns a zero vector. Linear velocity is often used for calculations (damping, direction, etc) and must be cloned to avoid unwanted effects in the Physics engine.

b2Body_GetLinearVelocity(bodyId: b2BodyId): b2Vec2
Parameters
bodyId (b2BodyId) The identifier for the body.
Returns
b2Vec2: The linear velocity vector of the body. Returns a zero vector (0,0) if the body state is null.

b2Body_GetAngularVelocity

Retrieves the current angular velocity of a body from its state in the physics world. Angular velocity represents how fast the body is rotating.

b2Body_GetAngularVelocity(bodyId: b2BodyId): number
Parameters
bodyId (b2BodyId) The identifier for the body.
Returns
number: The angular velocity in radians per second. Returns 0 if the body state cannot be retrieved.

b2Body_SetLinearVelocity

Sets the linear velocity of a body. If the body is static, the function returns without making changes. If the new velocity has a non-zero magnitude, the body will be awakened. The function will return early if the body state cannot be retrieved.

b2Body_SetLinearVelocity(bodyId: b2BodyId, linearVelocity: b2Vec2): void
Parameters
bodyId (b2BodyId) The identifier of the body to modify.
linearVelocity (b2Vec2) The new linear velocity vector to set.
Returns
void:

b2Body_SetAngularVelocity

Sets the angular velocity of a body. If the body is static or has fixed rotation, the function returns without making changes. The body is woken up if a non-zero angular velocity is set.

b2Body_SetAngularVelocity(bodyId: b2BodyId, angularVelocity: number): void
Parameters
bodyId (b2BodyId) The identifier of the body to modify
angularVelocity (number) The new angular velocity in radians per second
Returns
void:

b2Body_ApplyForce

Applies a force at a world point to a body. If the force is not applied at the center of mass, it will generate a torque and affect angular motion.

b2Body_ApplyForce(bodyId: b2BodyId, force: b2Vec2, point: b2Vec2, wake: boolean): void
Parameters
bodyId (b2BodyId) The identifier of the body to apply the force to
force (b2Vec2) The world force vector
point (b2Vec2) The world position of the point of application
wake (boolean) Whether to wake the body if it is sleeping
Returns
void:

b2Body_ApplyForceToCenter

Applies a force to the center of mass of a body. If the body is sleeping, it can optionally be woken up. The force is only applied if the body is in the awake set.

b2Body_ApplyForceToCenter(bodyId: b2BodyId, force: b2Vec2, wake: boolean): void
Parameters
bodyId (b2BodyId) The identifier of the body to apply the force to
force (b2Vec2) The world force vector to apply to the body's center
wake (boolean) Whether to wake the body if it is sleeping
Returns
void:

b2Body_ApplyTorque

Adds the specified torque to the body's total torque. If the wake parameter is true and the body is sleeping, it will be awakened. The torque is only applied if the body is in the awake set.

b2Body_ApplyTorque(bodyId: b2BodyId, torque: number, wake: boolean): void
Parameters
bodyId (b2BodyId) The identifier of the body to apply torque to
torque (number) The amount of torque to apply
wake (boolean) Whether to wake the body if it's sleeping
Returns
void:

b2Body_ApplyLinearImpulse

Applies a linear impulse to a body at a specified world point, affecting both its linear and angular velocities.

b2Body_ApplyLinearImpulse(bodyId: b2BodyId, impulse: b2Vec2, point: b2Vec2, wake: boolean): void
Parameters
bodyId (b2BodyId) The identifier of the body to apply the impulse to
impulse (b2Vec2) The world impulse vector to apply
point (b2Vec2) The world position where the impulse is applied
wake (boolean) Whether to wake the body if it's sleeping
Returns
void:
Throws
  • Error: Throws an assertion error if the body's local index is invalid

b2Body_ApplyLinearImpulseToCenter

Applies a linear impulse to the center of mass of a body. If the body is sleeping, it can optionally be woken up.

b2Body_ApplyLinearImpulseToCenter(bodyId: b2BodyId, impulse: b2Vec2, wake: boolean): void
Parameters
bodyId (b2BodyId) The identifier of the body to apply the impulse to
impulse (b2Vec2) The linear impulse vector to be applied
wake (boolean) Whether to wake the body if it's sleeping
Returns
void:

b2Body_ApplyAngularImpulse

Applies an angular impulse to a body, affecting its angular velocity. The impulse is scaled by the body's inverse inertia.

b2Body_ApplyAngularImpulse(bodyId: b2BodyId, impulse: number, wake: boolean): void
Parameters
bodyId (b2BodyId) The identifier of the body to apply the impulse to
impulse (number) The angular impulse to apply
wake (boolean) Whether to wake the body if it's sleeping
Returns
void:
Throws
  • Error: Throws an assertion error if the body ID is invalid or if the body revision doesn't match

b2Body_GetType

Retrieves the body type (static, kinematic, or dynamic) for a given body ID by looking up the body in the physics world using the provided identifier.

b2Body_GetType(bodyId: b2BodyId): b2BodyType
Parameters
bodyId (b2BodyId) The identifier for the body to query.
Returns
b2BodyType: The type of the specified body.

b2Body_SetType

Updates a body's type and handles all necessary simulation changes including:

  • Destroying existing contacts
  • Waking the body and connected bodies
  • Unlinking and relinking joints
  • Transferring the body between solver sets
  • Updating broad-phase proxies
  • Recalculating mass data If the body is disabled or the type is unchanged, minimal processing occurs. Special handling exists for transitions to/from static body type.
b2Body_SetType(bodyId: b2BodyId, type: b2BodyType): void
Parameters
bodyId (b2BodyId) The ID of the body to modify
type (b2BodyType) The new body type to set (static, kinematic, or dynamic)
Returns
void:

b2Body_SetUserData

Associates arbitrary user data with a physics body. The user data can be retrieved later and can be of any type. The body is located using its world identifier and the user data is stored directly on the body object.

b2Body_SetUserData(bodyId: b2BodyId, userData: any): void
Parameters
bodyId (b2BodyId) The identifier of the body to modify.
userData (any) The user data to associate with the body.
Returns
void:

b2Body_GetUserData

Retrieves the custom user data that was previously attached to the specified body. The function first gets the world from the body ID, then retrieves the full body object, and finally returns its user data.

b2Body_GetUserData(bodyId: b2BodyId): object
Parameters
bodyId (b2BodyId) The identifier for the body.
Returns
object: The user data associated with the body.

b2Body_GetMass

Retrieves the mass value from a body's simulation data by accessing the world and body objects using the provided body identifier.

b2Body_GetMass(bodyId: b2BodyId): number
Parameters
bodyId (b2BodyId) The identifier for the body whose mass is to be retrieved.
Returns
number: The mass of the body in kilograms.

b2Body_GetInertiaTensor

Retrieves the rotational inertia value from a body's simulation data using the body's ID. The inertia tensor represents the body's resistance to rotational acceleration.

b2Body_GetInertiaTensor(bodyId: b2BodyId): number
Parameters
bodyId (b2BodyId) The ID of the body to get the inertia tensor from.
Returns
number: The inertia tensor value of the body.

b2Body_GetLocalCenterOfMass

Returns a copy of the body's local center of mass position vector. The local center is expressed in the body's local coordinate system.

b2Body_GetLocalCenterOfMass(bodyId: b2BodyId): b2Vec2
Parameters
bodyId (b2BodyId) The identifier for the body.
Returns
b2Vec2: The local center of mass position vector.

b2Body_GetWorldCenterOfMass

Returns a copy of the body's center of mass position in world coordinates. The returned vector is a clone of the internal state, preventing external modification of the body's actual center position.

b2Body_GetWorldCenterOfMass(bodyId: b2BodyId): b2Vec2
Parameters
bodyId (b2BodyId) The identifier for the body whose center of mass position is being queried.
Returns
b2Vec2: A vector representing the world position of the body's center of mass.

b2Body_SetMassData

Sets the mass properties of a body including mass, rotational inertia, and center of mass. The function updates both the primary mass properties and derived values like inverse mass.

b2Body_SetMassData(bodyId: b2BodyId, massData: b2MassData): void
Parameters
bodyId (b2BodyId) The identifier for the body to modify
massData (b2MassData) An object containing:
  • mass: The mass of the body (must be >= 0)
  • rotationalInertia: The rotational inertia (must be >= 0)
  • center: A b2Vec2 representing the local center of mass
Returns
void:
Throws
  • Error: Throws assertion error if mass or rotationalInertia are invalid or negative, or if the center vector is invalid

b2Body_GetMassData

Retrieves the mass properties of a body, including its total mass, center of mass position, and rotational inertia.

b2Body_GetMassData(bodyId: b2BodyId): b2MassData
Parameters
bodyId (b2BodyId) The identifier for the body whose mass data is being retrieved
Returns
b2MassData: An object containing mass properties:
  • mass: The total mass of the body
  • center: A b2Vec2 representing the local center of mass
  • rotationalInertia: The rotational inertia about the local center of mass

b2Body_ApplyMassFromShapes

This function retrieves the body from the world using its ID and updates its mass data properties (mass, center of mass, and rotational inertia) based on the shapes attached to it. If the world cannot be accessed, the function returns without performing any operations.

b2Body_ApplyMassFromShapes(bodyId: b2BodyId): void
Parameters
bodyId (b2BodyId) The identifier for the body whose mass properties need to be updated.
Returns
void:

b2Body_SetLinearDamping

Sets the linear damping coefficient for a body, which reduces its linear velocity over time. Linear damping is used to simulate air resistance or fluid friction.

b2Body_SetLinearDamping(bodyId: b2BodyId, linearDamping: number): void
Parameters
bodyId (b2BodyId) The identifier for the body to modify.
linearDamping (number) The new linear damping value. Must be non-negative.
Returns
void:
Throws
  • Error: Throws an assertion error if linearDamping is invalid or negative.

b2Body_GetLinearDamping

Returns the linear damping coefficient that reduces the body's linear velocity. Linear damping is used to reduce the linear velocity of the body in the absence of forces. The damping parameter can be used to simulate fluid/air resistance.

b2Body_GetLinearDamping(bodyId: b2BodyId): number
Parameters
bodyId (b2BodyId) The identifier for the body.
Returns
number: The linear damping coefficient of the body.

b2Body_SetAngularDamping

Sets the angular damping coefficient for a body, which reduces its angular velocity over time. Angular damping is a value between 0 and infinity that reduces the body's angular velocity.

b2Body_SetAngularDamping(bodyId: b2BodyId, angularDamping: number): void
Parameters
bodyId (b2BodyId) The identifier for the target body.
angularDamping (number) The new angular damping value. Must be non-negative.
Returns
void:
Throws
  • Error: Throws an assertion error if angularDamping is invalid or negative.

b2Body_GetAngularDamping

Returns the angular damping coefficient that reduces the body's angular velocity over time. Angular damping is specified in the range [0,1].

b2Body_GetAngularDamping(bodyId: b2BodyId): number
Parameters
bodyId (b2BodyId) The identifier for the body.
Returns
number: The angular damping coefficient of the body.

b2Body_SetGravityScale

Sets a scale factor that modifies the effect of gravity on a specific body. A value of 1.0 indicates normal gravity, 0.0 indicates no gravity, and negative values reverse the effect of gravity on the body.

b2Body_SetGravityScale(bodyId: b2BodyId, gravityScale: number): void
Parameters
bodyId (b2BodyId) The identifier for the body to modify.
gravityScale (number) The scaling factor to apply to gravity for this body.
Returns
void:
Throws
  • Error: Throws an assertion error if bodyId is invalid or if gravityScale is not a valid number.

b2Body_GetGravityScale

Gets the gravity scale of a body.

b2Body_GetGravityScale(bodyId: b2BodyId): number
Parameters
bodyId (b2BodyId) The identifier of the body to query.
Returns
number: The gravity scale factor of the body.
Throws
  • Error: Throws an assertion error if the bodyId is invalid.

b2Body_IsAwake

Determines if a body is currently in the awake set by checking its set index against the b2_awakeSet type. Bodies in the awake set are actively participating in the simulation.

b2Body_IsAwake(bodyId: b2BodyId): boolean
Parameters
bodyId (b2BodyId) The identifier for the body to check.
Returns
boolean: True if the body is in the awake set, false otherwise.

b2Body_SetAwake

Controls whether a physics body is awake (active) or asleep (inactive). When setting a body to sleep, it will split islands if there are pending constraint removals. When waking a body, it will be moved from the sleeping set to the awake set.

b2Body_SetAwake(bodyId: b2BodyId, awake: boolean): void
Parameters
bodyId (b2BodyId) The ID of the body to modify
awake (boolean) True to wake the body, false to put it to sleep
Returns
void:

b2Body_IsEnabled

Determines if a physics body is enabled by checking if it belongs to the disabled set. A disabled body does not participate in collision detection or dynamics simulation.

b2Body_IsEnabled(bodyId: b2BodyId): boolean
Parameters
bodyId (b2BodyId) The identifier for the body to check.
Returns
boolean: True if the body is enabled, false if disabled.

b2Body_IsSleepEnabled

Returns whether the specified body has sleep enabled. When sleep is enabled, the body can automatically enter a sleep state when it becomes inactive.

b2Body_IsSleepEnabled(bodyId: b2BodyId): boolean
Parameters
bodyId (b2BodyId) The identifier for the body to check.
Returns
boolean: True if sleep is enabled for the body, false otherwise.

b2Body_SetSleepThreshold

Sets the minimum velocity threshold that determines when a body can transition to a sleeping state. When a body's velocity falls below this threshold, it becomes eligible for sleeping.

b2Body_SetSleepThreshold(bodyId: b2BodyId, sleepVelocity: number): void
Parameters
bodyId (b2BodyId) The identifier for the body to modify.
sleepVelocity (number) The velocity threshold below which the body can sleep.
Returns
void:

b2Body_GetSleepThreshold

Returns the minimum speed threshold below which a body can be put to sleep to optimize simulation performance.

b2Body_GetSleepThreshold(bodyId: b2BodyId): number
Parameters
bodyId (b2BodyId) The identifier for the body.
Returns
number: The sleep threshold value for the body.

b2Body_EnableSleep

Enables or disables sleep capability for a specific body. When sleep is disabled, the body will be woken if it was sleeping.

b2Body_EnableSleep(bodyId: b2BodyId, enableSleep: boolean): void
Parameters
bodyId (b2BodyId) The identifier for the body to modify
enableSleep (boolean) True to enable sleep capability, false to disable it
Returns
void:
Throws
  • Error: If the world associated with the bodyId is not found

b2Body_Disable

Disables a body in the physics simulation by removing it from its current solver set and moving it to the disabled set. The function removes all contacts associated with the body, removes it from any island it belongs to, destroys shape proxies in the broad phase, and transfers associated joints to the disabled set.

b2Body_Disable(bodyId: b2BodyId): void
Parameters
bodyId (b2BodyId) The identifier of the body to disable
Returns
void:
Throws
  • Error: Throws if the world is locked or invalid

b2Body_Enable

Enables a previously disabled body in the physics world. When enabled, the body's shapes are added to the broad-phase collision system, and its joints are reconnected to the simulation. The body is moved from the disabled set to either the static set or awake set based on its type.

b2Body_Enable(bodyId: b2BodyId): void
Parameters
bodyId (b2BodyId) The identifier of the body to enable
Returns
void:
Throws
  • Error: Throws an assertion error if joint connectivity validation fails

b2Body_SetFixedRotation

Sets the fixed rotation state of a body. When enabled, the body will not rotate and any existing angular velocity is cleared. The body's mass data is updated to reflect the change in rotational constraints.

b2Body_SetFixedRotation(bodyId: b2BodyId, flag: boolean): void
Parameters
bodyId (b2BodyId) The identifier for the body to modify
flag (boolean) True to fix the rotation, false to allow rotation
Returns
void:

b2Body_IsFixedRotation

Checks whether a body has fixed rotation enabled. When fixed rotation is enabled, the body will not rotate in response to torques or collisions.

b2Body_IsFixedRotation(bodyId: b2BodyId): boolean
Parameters
bodyId (b2BodyId) The identifier for the body to check
Returns
boolean: True if the body has fixed rotation enabled, false otherwise

b2Body_SetBullet

Sets whether a body should be treated as a bullet for continuous collision detection. Bullet bodies are designed for fast moving objects that require more precise collision detection.

b2Body_SetBullet(bodyId: b2BodyId, flag: boolean): void
Parameters
bodyId (b2BodyId) The identifier for the physics body.
flag (boolean) True to enable bullet mode, false to disable it.
Returns
void:

b2Body_IsBullet

Retrieves the bullet status of a body from the physics simulation. Bullet bodies undergo continuous collision detection for improved accuracy with fast-moving objects.

b2Body_IsBullet(bodyId: b2BodyId): boolean
Parameters
bodyId (b2BodyId) The identifier for the body to check.
Returns
boolean: True if the body is a bullet, false otherwise.

b2Body_EnableHitEvents

Enables or disables hit event detection for all shapes attached to a body.

b2Body_EnableHitEvents(bodyId: b2BodyId, enableHitEvents: boolean): void
Parameters
bodyId (b2BodyId) The identifier of the body to modify
enableHitEvents (boolean) Whether to enable or disable hit events
Returns
void:

b2Body_GetShapeCount

Returns the total count of shapes currently attached to the specified body in the physics world.

b2Body_GetShapeCount(bodyId: b2BodyId): number
Parameters
bodyId (b2BodyId) The identifier for the body to query.
Returns
number: The number of shapes attached to the body.

b2Body_GetShapes

Retrieves all shapes attached to the specified body by traversing the linked list of shapes starting from the body's headShapeId. Each shape ID is stored in the provided shapeArray and the total count is returned. If shapeArray is already large enough we can avoid the overhead of growing the array.

b2Body_GetShapes(bodyId: b2BodyId, shapeArray: Array<b2ShapeId>): number
Parameters
bodyId (b2BodyId) The identifier of the body to get shapes from.
shapeArray (Array<b2ShapeId>) An array to store the retrieved shape IDs.
Returns
number: The number of shapes found on the body.

b2Body_GetJointCount

Returns the total count of joints that are connected to the specified body.

b2Body_GetJointCount(bodyId: b2BodyId): number
Parameters
bodyId (b2BodyId) The identifier for the body to query.
Returns
number: The number of joints connected to the body.

b2Body_GetJoints

Retrieves the IDs of all joints connected to the specified body, up to the given capacity. The joint IDs are stored in the provided jointArray. The function traverses the body's joint list and copies each joint's ID information including the index, world ID and revision.

b2Body_GetJoints(bodyId: b2BodyId, jointArray: Array<b2JointId>, capacity: number): number
Parameters
bodyId (b2BodyId) The ID of the body to get joints for
jointArray (Array<b2JointId>) Array to store the joint IDs
capacity (number) Maximum number of joints to retrieve
Returns
number: The number of joints found and stored in jointArray

Core

Core

Core

b2SetLengthUnitsPerMeter

Sets the global scaling factor that defines how many length units in the physics simulation correspond to one meter in the real world. This affects all subsequent physics calculations in the Box2D engine.

b2SetLengthUnitsPerMeter(lengthUnits: number): void
Parameters
lengthUnits (number) The number of length units that represent one meter.
Returns
void:

b2GetLengthUnitsPerMeter

Returns the value of b2_lengthUnitsPerMeter, which defines the conversion factor between physics simulation units and real-world meters.

b2GetLengthUnitsPerMeter(): number
Returns
number: The number of length units per meter used in the physics simulation.

b2SetAssertFcn

This function sets the global assertion handler used by Box2D for runtime checks. The assertion handler is called when a Box2D assertion fails.

b2SetAssertFcn(assertFcn: (Function | null)): void
Parameters
assertFcn ((Function | null)) The assertion function to handle Box2D assertions. If null, assertions will be disabled.
Returns
void:

b2GetVersion

This function creates and returns a new b2Version object initialized with Box2D version 3.0.0

b2GetVersion(): b2Version
Returns
b2Version: A b2Version object containing major version 3, minor version 0, and revision 0

b2SetAllocator

This function is intended to set custom memory allocation and deallocation functions for Box2D. However, in the Phaser Box2D JS implementation, this functionality is not supported and will only generate a warning message.

b2SetAllocator(allocFcn: Function, freeFcn: Function): void
Parameters
allocFcn (Function) Memory allocation function pointer
freeFcn (Function) Memory deallocation function pointer
Returns
void:
Throws
  • Warning: Outputs a console warning indicating lack of support

b2GetByteCount

This function is a stub that warns users that byte count tracking is not supported in the JavaScript implementation of Box2D for Phaser.

b2GetByteCount(): number
Returns
number: An integer representing the total bytes used by Box2D.

b2CreateTimer

This function creates a timer object but is not supported in the Phaser Box2D JS implementation. When called, it issues a console warning about lack of support.

b2CreateTimer(): b2Timer
Returns
b2Timer: A timer object for measuring elapsed time.

b2GetTicks

This is a stub function that exists for compatibility with Box2D but is not implemented in the Phaser Box2D JS port. It logs a warning when called.

b2GetTicks(): number
Returns
number: Returns 0 since this function not supported
Throws
  • Warning: Logs a console warning that the function is not supported

b2GetMilliseconds

This function is a stub that warns that millisecond timing is not supported in the Phaser Box2D JS implementation.

b2GetMilliseconds(): number
Returns
number: The elapsed time in milliseconds.
Throws
  • Warning: Console warning indicating lack of support.

b2GetMillisecondsAndReset

This function returns the elapsed milliseconds from a Box2D timer object and resets it. In the JavaScript implementation for Phaser Box2D, this functionality is not supported and will trigger a warning.

b2GetMillisecondsAndReset(timer: b2Timer): number
Parameters
timer (b2Timer) The Box2D timer object to query and reset
Returns
number: The elapsed time in milliseconds
Throws
  • Warning: Logs a console warning that this function is not supported

b2SleepMilliseconds

This function is a stub that issues a warning message when called, as the sleep functionality is not supported in the Phaser Box2D JS implementation.

b2SleepMilliseconds(ms: number): void
Parameters
ms (number) The number of milliseconds to sleep
Returns
void:

b2Yield

This function serves as a placeholder for Box2D's b2Yield functionality, which is not supported in the Phaser Box2D JS implementation. When called, it emits a warning to the console.

b2Yield(): void
Returns
void:

DebugDraw

DebugDraw

DebugDraw

CreateDebugDraw

Creates a debug drawing interface for Box2D that renders shapes to a canvas context.
The canvas is automatically sized to 1280x720 or 720x1280 based on window orientation.
All coordinates are transformed from Box2D world space to screen space.
This feature isn't meant for production. It is purely for debugging and testing. The code is not optimized, stable or extensible. Implement your own drawing code for production.

CreateDebugDraw(canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D, scale: number): b2DebugDraw
Parameters
canvas (HTMLCanvasElement) The canvas element to draw on
ctx (CanvasRenderingContext2D) The 2D rendering context for the canvas
scale (number = 20) The scale factor to convert Box2D coordinates to pixels
Returns
b2DebugDraw: A debug draw instance with methods for rendering Box2D shapes The debug draw instance includes methods for drawing:
  • Polygons (outlined and filled)
  • Circles (outlined and filled)
  • Capsules (outlined and filled)
  • Images mapped to shapes
  • Line segments
  • Points
  • Transforms

RAF

Creates an animation loop using requestAnimationFrame that tracks timing information and FPS. The callback is invoked each frame with the time delta, total time, and current FPS. Frame delta time is capped at 100ms to avoid large time steps.

RAF(callback: function)
Parameters
callback (function) Function to call each frame with signature (deltaTime, totalTime, currentFps)
Name Description
callback.deltaTime number Time elapsed since last frame in seconds, capped at 0.1s
callback.totalTime number Total accumulated time in seconds
callback.currentFps number Current frames per second, updated once per second

AttachImage

Attaches an image to the last shape of a Box2D body. The function loads a PNG image asynchronously and sets up drawing parameters including offset, scale, and source rectangle coordinates. The image is stored in the shape's properties for later rendering.

AttachImage(worldId: number, bodyId: number, path: string, imgName: string, drawOffset: b2Vec2, drawScale: b2Vec2, sourcePosition: b2Vec2, sourceSize: b2Vec2): Object
Parameters
worldId (number) The ID of the Box2D world
bodyId (number) The ID of the body to attach the image to
path (string) Directory path where the image is located
imgName (string) Name of the image file
drawOffset (b2Vec2 = null) Offset vector for drawing the image
drawScale (b2Vec2 = null) Scale vector for drawing the image
sourcePosition (b2Vec2 = null) Position in the source image to start drawing from
sourceSize (b2Vec2 = null) Size of the region to draw from the source image
Returns
Object: The modified shape object with attached image properties

ConvertScreenToWorld

Converts screen/canvas coordinates to world space coordinates in the Box2D physics system.

ConvertScreenToWorld(canvas: HTMLCanvasElement, drawScale: number, ps: Object): b2Vec2
Parameters
canvas (HTMLCanvasElement) The canvas element being used for rendering
drawScale (number) The scale factor between screen and world coordinates
ps (Object) The screen position coordinates
Returns
b2Vec2: A vector containing the world space coordinates
Example
// Convert mouse click position to world coordinates
const worldPos = ConvertScreenToWorld(myCanvas, 30, mousePos);

ConvertWorldToScreen

Transforms a position from world space to screen space, taking into account the canvas dimensions, aspect ratio, and zoom level. The function maps the world coordinates to normalized coordinates (0-1) and then scales them to screen pixels.

ConvertWorldToScreen(canvas: HTMLCanvasElement, drawScale: number, pw: b2Vec2): b2Vec2
Parameters
canvas (HTMLCanvasElement) The canvas element used for rendering
drawScale (number) The scale factor for converting world units to pixels
pw (b2Vec2) The world position to convert
Returns
b2Vec2: The converted screen coordinates as a b2Vec2

Distance

Distance

Distance

b2GetSweepTransform

Calculates an intermediate transform by linearly interpolating between two states defined in a sweep motion. The resulting transform accounts for both translation and rotation, adjusted by the local center offset.

b2GetSweepTransform(sweep: b2Sweep, time: number): b2Transform
Parameters
sweep (b2Sweep) A sweep object containing initial (c1, q1) and final (c2, q2) positions and rotations, along with a local center offset.
time (number) Interpolation factor between 0 and 1, where 0 represents the initial state and 1 represents the final state.
Returns
b2Transform: A transform object containing the interpolated position (p) and rotation (q) at the specified time.

b2SegmentDistance

Calculates the minimum distance between two line segments defined by their endpoints.

b2SegmentDistance(p1X: number, p1Y: number, q1X: number, q1Y: number, p2X: number, p2Y: number, q2X: number, q2Y: number): b2SegmentDistanceResult
Parameters
p1X (number) X coordinate of the first point of segment 1
p1Y (number) Y coordinate of the first point of segment 1
q1X (number) X coordinate of the second point of segment 1
q1Y (number) Y coordinate of the second point of segment 1
p2X (number) X coordinate of the first point of segment 2
p2Y (number) Y coordinate of the first point of segment 2
q2X (number) X coordinate of the second point of segment 2
q2Y (number) Y coordinate of the second point of segment 2
Returns
b2SegmentDistanceResult: An object containing:
  • fraction1: {number} Parameter along segment 1 for closest point (0-1)
  • fraction2: {number} Parameter along segment 2 for closest point (0-1)
  • distanceSquared: {number} Square of the minimum distance between segments

b2MakeProxy

b2MakeProxy(vertices: Array<b2Vec2>, count: number, radius: number): b2DistanceProxy
Parameters
vertices (Array<b2Vec2>) Array of 2D vectors representing the vertices
count (number) Number of vertices to process (max B2_MAX_POLYGON_VERTICES)
radius (number) Radius value for the proxy
Returns
b2DistanceProxy: A new distance proxy containing the processed vertices
Throws
  • Error: Throws assertion error if count exceeds B2_MAX_POLYGON_VERTICES

b2MakeProxy

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2MakeProxy

b2ShapeDistance

Computes the distance between two convex shapes using the GJK (Gilbert-Johnson-Keerthi) algorithm.

b2ShapeDistance(cache: b2DistanceCache, input: b2DistanceInput, simplexes: Array<b2Simplex>, simplexCapacity: number): b2DistanceOutput
Parameters
cache (b2DistanceCache) Cache object to store and retrieve simplex data between calls
input (b2DistanceInput) Input parameters containing:
  • proxyA: First shape proxy
  • proxyB: Second shape proxy
  • transformA: Transform for first shape
  • transformB: Transform for second shape
  • useRadii: Boolean flag for including shape radii in calculation
simplexes (Array<b2Simplex>) Optional array to store simplex history
simplexCapacity (number) Maximum number of simplexes to store
Returns
b2DistanceOutput: Output containing:
  • pointA: Closest point on shape A
  • pointB: Closest point on shape B
  • distance: Distance between the shapes
  • iterations: Number of iterations performed
  • simplexCount: Number of simplexes stored

b2ShapeCast

Uses an iterative algorithm to determine if and when two convex shapes will collide during a linear motion. Shape B is translated while shape A remains stationary. The algorithm uses support points and simplexes to determine the closest points between the shapes.

b2ShapeCast(input: b2ShapeCastPairInput): b2CastOutput
Parameters
input (b2ShapeCastPairInput) Contains: proxyA - First shape proxy proxyB - Second shape proxy transformA - Transform of first shape transformB - Transform of second shape translationB - Translation vector for second shape maxFraction - Maximum fraction of motion to check
Returns
b2CastOutput: Contains: fraction - Time of impact fraction [0,maxFraction] point - Point of impact normal - Surface normal at impact iterations - Number of iterations used hit - Whether a collision was detected

b2TimeOfImpact

Computes when two moving shapes first collide during their motion sweeps. Uses conservative advancement and binary search to find the first time of impact or determine that no impact occurs during the time interval.

b2TimeOfImpact(input: b2TOIInput): b2TOIOutput
Parameters
input (b2TOIInput) Input parameters containing:
  • proxyA: First shape proxy
  • proxyB: Second shape proxy
  • sweepA: Motion sweep for first shape
  • sweepB: Motion sweep for second shape
  • tMax: Maximum time interval
Returns
b2TOIOutput: Output containing:
  • state: The termination state (Unknown, Failed, Overlapped, Hit, Separated)
  • t: Time of impact (between 0 and tMax)
Throws
  • Error: Throws assertion error if input sweeps are not normalized

DistanceJoint

DistanceJoint

DistanceJoint

b2DistanceJoint_SetLength

Sets the target length of a distance joint. The length value is automatically clamped between b2_linearSlop and B2_HUGE. After setting the length, the joint's impulse values are reset to zero.

b2DistanceJoint_SetLength(jointId: b2JointId, length: number): void
Parameters
jointId (b2JointId) The identifier of the distance joint to modify.
length (number) The desired length of the joint, clamped between b2_linearSlop and B2_HUGE.
Returns
void:
Throws
  • Error: Throws if the joint type is not b2_distanceJoint.

b2DistanceJoint_SetLength

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2DistanceJoint_SetLength

b2DistanceJoint_GetLength

Returns the current length of a distance joint. The joint must be of type b2_distanceJoint.

b2DistanceJoint_GetLength(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the distance joint.
Returns
number: The current length of the distance joint.
Throws
  • Error: Throws an error if the joint is not of type b2_distanceJoint.

b2DistanceJoint_EnableLimit

Sets the enable/disable state of the limit constraint for a distance joint. The joint must be of type b2_distanceJoint or an error will occur.

b2DistanceJoint_EnableLimit(jointId: b2JointId, enableLimit: boolean): void
Parameters
jointId (b2JointId) The identifier for the distance joint to modify.
enableLimit (boolean) True to enable the joint's limit, false to disable it.
Returns
void:
Throws
  • Error: Throws an error if the joint type is not b2_distanceJoint.

b2DistanceJoint_IsLimitEnabled

b2DistanceJoint_IsLimitEnabled(jointId: b2JointId): boolean
Parameters
jointId (b2JointId) The identifier for the distance joint to check.
Returns
boolean: True if the limit is enabled, false otherwise.
Throws
  • Error: Throws an error if the joint is not a distance joint.

b2DistanceJoint_SetLengthRange

Sets the minimum and maximum length constraints for a distance joint. The values are clamped between b2_linearSlop and B2_HUGE. The function resets all impulse values to zero after updating the length range.

b2DistanceJoint_SetLengthRange(jointId: b2JointId, minLength: number, maxLength: number): void
Parameters
jointId (b2JointId) The identifier for the distance joint
minLength (number) The minimum allowed length of the joint
maxLength (number) The maximum allowed length of the joint
Returns
void:
Throws
  • Error: If the joint type is not b2_distanceJoint

b2DistanceJoint_GetMinLength

Gets the minimum length of a distance joint.

b2DistanceJoint_GetMinLength(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the distance joint.
Returns
number: The minimum length value of the distance joint.
Throws
  • Error: If the joint type is not b2_distanceJoint.

b2DistanceJoint_GetMaxLength

Gets the maximum length of a distance joint.

b2DistanceJoint_GetMaxLength(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the distance joint.
Returns
number: The maximum length value of the distance joint.
Throws
  • Error: If the joint is not of type b2_distanceJoint.

b2DistanceJoint_GetCurrentLength

Calculates the current distance between the two anchor points of a distance joint in world coordinates. The function transforms the local anchor points of both bodies to world coordinates and computes the distance between them.

b2DistanceJoint_GetCurrentLength(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the distance joint
Returns
number: The current length between the two anchor points of the distance joint
Throws
  • Error: Returns 0 if the world is locked

b2DistanceJoint_EnableSpring

Sets the spring behavior state of a distance joint. When enabled, the joint acts like a spring between two bodies. When disabled, the joint maintains a fixed distance between the connected bodies.

b2DistanceJoint_EnableSpring(jointId: b2JointId, enableSpring: boolean): void
Parameters
jointId (b2JointId) The identifier of the distance joint to modify.
enableSpring (boolean) True to enable spring behavior, false to disable it.
Returns
void:
Throws
  • Error: Throws an error if the joint is not of type b2_distanceJoint.

b2DistanceJoint_IsSpringEnabled

Returns the state of the spring enable flag for the specified distance joint. The function validates that the joint is of type b2_distanceJoint before accessing the spring enable property.

b2DistanceJoint_IsSpringEnabled(jointId: b2JointId): boolean
Parameters
jointId (b2JointId) The identifier for the distance joint to check.
Returns
boolean: True if the spring mechanism is enabled, false otherwise.
Throws
  • Error: Throws an error if the joint is not of type b2_distanceJoint.

b2DistanceJoint_SetSpringHertz

Sets the spring oscillation frequency for a distance joint. The frequency determines how quickly the spring oscillates when disturbed from equilibrium.

b2DistanceJoint_SetSpringHertz(jointId: b2JointId, hertz: number): void
Parameters
jointId (b2JointId) The identifier for the distance joint to modify.
hertz (number) The spring frequency in Hertz (oscillations per second).
Returns
void:
Throws
  • Error: Throws an error if the joint is not a distance joint.

b2DistanceJoint_SetSpringDampingRatio

Sets the damping ratio parameter for a distance joint's spring mechanism. The joint must be of type b2_distanceJoint.

b2DistanceJoint_SetSpringDampingRatio(jointId: b2JointId, dampingRatio: number): void
Parameters
jointId (b2JointId) The identifier for the distance joint to modify
dampingRatio (number) The damping ratio for the spring (0 = no damping, 1 = critical damping)
Returns
void:
Throws
  • Error: Throws if the joint type is not b2_distanceJoint

b2DistanceJoint_GetHertz

Gets the hertz frequency parameter of a distance joint.

b2DistanceJoint_GetHertz(jointId: number): number
Parameters
jointId (number) The identifier for the distance joint.
Returns
number: The hertz frequency value of the distance joint.
Throws
  • Error: If the joint is not a distance joint or the jointId is invalid.

b2DistanceJoint_GetDampingRatio

Gets the damping ratio of a distance joint.

b2DistanceJoint_GetDampingRatio(jointId: number): number
Parameters
jointId (number) The identifier for the distance joint.
Returns
number: The damping ratio of the distance joint.
Throws
  • Error: If the joint is not a distance joint or the jointId is invalid.

b2DistanceJoint_EnableMotor

Enables or disables the motor on a distance joint. When the motor state changes, the motor impulse is reset to zero.

b2DistanceJoint_EnableMotor(jointId: b2JointId, enableMotor: boolean): void
Parameters
jointId (b2JointId) The identifier for the distance joint
enableMotor (boolean) True to enable the motor, false to disable it
Returns
void:
Throws
  • Error: If the joint is not a distance joint type

b2DistanceJoint_IsMotorEnabled

b2DistanceJoint_IsMotorEnabled(jointId: b2JointId): boolean
Parameters
jointId (b2JointId) The identifier for the distance joint to check.
Returns
boolean: True if the motor is enabled, false otherwise.
Throws
  • Error: Throws an error if the joint is not a distance joint.

b2DistanceJoint_SetMotorSpeed

Sets the motor speed for a distance joint.

b2DistanceJoint_SetMotorSpeed(jointId: b2JointId, motorSpeed: number): void
Parameters
jointId (b2JointId) The identifier for the distance joint to modify.
motorSpeed (number) The new motor speed value to set.
Returns
void:
Throws
  • Error: Throws if the joint is not a distance joint type.

b2DistanceJoint_GetMotorSpeed

Gets the motor speed of a distance joint.

b2DistanceJoint_GetMotorSpeed(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the distance joint.
Returns
number: The current motor speed of the distance joint in radians per second.
Throws
  • Error: If the joint is not a distance joint or the joint ID is invalid.

b2DistanceJoint_GetMotorForce

Calculates the motor force by dividing the joint's motor impulse by the inverse time step (inv_h). The joint must be of type b2_distanceJoint.

b2DistanceJoint_GetMotorForce(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the distance joint.
Returns
number: The current motor force in Newtons, calculated as the motor impulse divided by the step time.
Throws
  • Error: Throws if the joint type is not b2_distanceJoint.

b2DistanceJoint_SetMaxMotorForce

Sets the maximum motor force for a distance joint.

b2DistanceJoint_SetMaxMotorForce(jointId: b2JointId, force: number): void
Parameters
jointId (b2JointId) The identifier for the distance joint to modify.
force (number) The maximum force the motor can generate.
Returns
void:
Throws
  • Error: Throws if the joint is not a distance joint type.

b2DistanceJoint_GetMaxMotorForce

Gets the maximum motor force of a distance joint.

b2DistanceJoint_GetMaxMotorForce(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the distance joint.
Returns
number: The maximum force that can be applied by the joint's motor.
Throws
  • Error: If the joint is not a distance joint or the joint ID is invalid.

DynamicTree

DynamicTree

DynamicTree

b2DynamicTree_Create

Creates a b2DynamicTree data structure used for efficient spatial partitioning. The tree is initialized with a pre-allocated pool of nodes linked in a free list.

b2DynamicTree_Create(): b2DynamicTree
Returns
b2DynamicTree: A new dynamic tree with:
  • Initial node capacity of 16
  • Empty root (B2_NULL_INDEX)
  • Initialized node array with parent/next pointers
  • All nodes set to height -1
  • Free list starting at index 0
  • Zero proxy count
  • Null leaf indices and centers
  • Zero rebuild capacity

b2DynamicTree_Destroy

Clears the nodes, leaf indices, and leaf centers arrays of the dynamic tree, effectively destroying the tree's data structure.

b2DynamicTree_Destroy(tree: b2DynamicTree): void
Parameters
tree (b2DynamicTree) The dynamic tree to destroy.
Returns
void:

b2DynamicTree_CreateProxy

Creates a proxy in a dynamic tree for collision detection. The proxy is added as a leaf node.

b2DynamicTree_CreateProxy(tree: b2DynamicTree, aabb: b2AABB, categoryBits: number, userData: number): number
Parameters
tree (b2DynamicTree) The dynamic tree to add the proxy to
aabb (b2AABB) The axis-aligned bounding box for the proxy
categoryBits (number) The collision category bits for filtering
userData (number) User data associated with this proxy
Returns
number: The ID of the created proxy node
Throws
  • Error: Throws assertion error if AABB bounds are outside valid range

b2DynamicTree_DestroyProxy

Removes a leaf node from the tree, frees the node's memory, and decrements the proxy count. The proxy must be a valid leaf node in the tree.

b2DynamicTree_DestroyProxy(tree: b2DynamicTree, proxyId: number): void
Parameters
tree (b2DynamicTree) The dynamic tree containing the proxy
proxyId (number) The ID of the proxy to destroy (must be >= 0 and < nodeCapacity)
Returns
void:
Throws
  • Error: Throws an assertion error if:
    • proxyId is out of bounds
    • the node is not a leaf
    • the tree has no proxies

b2DynamicTree_GetProxyCount

Returns the number of proxies currently stored in the dynamic tree by accessing the proxyCount property.

b2DynamicTree_GetProxyCount(tree: b2DynamicTree): number
Parameters
tree (b2DynamicTree) The dynamic tree to query.
Returns
number: The total count of proxies in the tree.

b2DynamicTree_MoveProxy

Updates the position of a proxy in the dynamic tree by removing and reinserting it with a new AABB.

b2DynamicTree_MoveProxy(tree: b2DynamicTree, proxyId: number, aabb: b2AABB): void
Parameters
tree (b2DynamicTree) The dynamic tree containing the proxy
proxyId (number) The ID of the proxy to move (must be within tree.nodeCapacity)
aabb (b2AABB) The new axis-aligned bounding box for the proxy
Returns
void:
Throws
  • Error: Throws assertion errors if:
    • The AABB is invalid
    • The AABB dimensions exceed B2_HUGE
    • The proxyId is out of bounds
    • The node at proxyId is not a leaf node

b2DynamicTree_EnlargeProxy

Updates a proxy's AABB in the dynamic tree and rebalances the tree structure by enlarging parent nodes' AABBs as needed.

b2DynamicTree_EnlargeProxy(tree: b2DynamicTree, proxyId: number, aabb: b2AABB): void
Parameters
tree (b2DynamicTree) The dynamic tree containing the proxy
proxyId (number) The ID of the proxy to enlarge
aabb (b2AABB) The new axis-aligned bounding box for the proxy
Returns
void:
Throws
  • Error: Throws assertion errors if:
    • The AABB is invalid
    • The AABB dimensions exceed B2_HUGE
    • The proxyId is out of bounds
    • The node is not a leaf
    • The new AABB is contained within the old one

b2DynamicTree_GetHeight

Returns the height of the specified dynamic tree by accessing the height property of the root node. The height represents the maximum number of levels from the root to any leaf node.

b2DynamicTree_GetHeight(tree: b2DynamicTree): number
Parameters
tree (b2DynamicTree) The dynamic tree to measure
Returns
number: The height of the tree. Returns 0 if the tree is empty (root is null)

b2DynamicTree_GetAreaRatio

Computes the sum of all internal node perimeters (excluding leaves and root) divided by the root node perimeter. This ratio provides a measure of the tree's spatial organization.

b2DynamicTree_GetAreaRatio(tree: b2DynamicTree): number
Parameters
tree (b2DynamicTree) The dynamic tree structure to analyze
Returns
number: The ratio of total internal node perimeter to root perimeter. Returns 0 if the tree is empty.

b2DynamicTree_Validate

Performs validation checks on a b2DynamicTree data structure to ensure its internal state is consistent. This is typically used for debugging and testing purposes.

b2DynamicTree_Validate(tree: b2DynamicTree): void
Parameters
tree (b2DynamicTree) The dynamic tree to validate
Returns
void:

b2DynamicTree_GetMaxBalance

Iterates through all non-leaf nodes in the tree and calculates the absolute height difference between their child nodes. Returns the largest height difference found.

b2DynamicTree_GetMaxBalance(tree: b2DynamicTree): number
Parameters
tree (b2DynamicTree) The dynamic tree to analyze
Returns
number: The maximum balance value (height difference) found between any pair of sibling nodes

b2DynamicTree_RebuildBottomUp

Rebuilds a dynamic tree from the bottom up by iteratively combining nodes with the lowest perimeter cost. The function first identifies all leaf nodes, then pairs them based on minimum combined AABB perimeter, creating parent nodes until a single root node remains.

b2DynamicTree_RebuildBottomUp(tree: b2DynamicTree): void
Parameters
tree (b2DynamicTree) The dynamic tree to rebuild
Returns
void:

b2DynamicTree_ShiftOrigin

Updates the axis-aligned bounding boxes (AABBs) of all nodes in the tree by subtracting the newOrigin vector from both their lower and upper bounds.

b2DynamicTree_ShiftOrigin(tree: b2DynamicTree, newOrigin: b2Vec2): void
Parameters
tree (b2DynamicTree) The dynamic tree whose nodes will be shifted
newOrigin (b2Vec2) The vector to subtract from all node boundaries
Returns
void:

b2DynamicTree_GetByteCount

Calculates the memory footprint by summing:

  • Base object properties
  • Node array storage
  • Rebuild capacity storage
b2DynamicTree_GetByteCount(tree: b2DynamicTree): number
Parameters
tree (b2DynamicTree) The dynamic tree instance to measure.
Returns
number: The estimated memory usage in bytes.

b2DynamicTree_Query

Queries a dynamic tree to find all nodes that overlap with the given AABB and match the category mask bits. Uses a stack-based traversal to efficiently search the tree structure.

b2DynamicTree_Query(tree: b2DynamicTree, aabb: b2AABB, maskBits: number, callback: function, context: any): void
Parameters
tree (b2DynamicTree) The dynamic tree to query
aabb (b2AABB) The axis-aligned bounding box to test for overlaps
maskBits (number) Category bits used to filter nodes
callback (function) Function called for each overlapping leaf node. Return false to terminate early, true to continue.
context (any) User context data passed to the callback function
Returns
void:

b2DynamicTree_RayCast

Traverses the dynamic tree and finds all leaf nodes that intersect with the input ray. For each intersection, calls the callback function which can control continuation of the search. Uses an AABB overlap test and separating axis test to efficiently cull branches.

b2DynamicTree_RayCast(tree: b2DynamicTree, input: b2RayCastInput, maskBits: number, callback: Function, context: any)
Parameters
tree (b2DynamicTree) The dynamic tree to query
input (b2RayCastInput) Input parameters for the ray cast including:
  • origin: b2Vec2 starting point
  • translation: b2Vec2 ray direction and length
  • maxFraction: number maximum ray length multiplier
maskBits (number) Bit mask to filter nodes by category
callback (Function) Function called for each leaf node intersection
  • Parameters: (input: b2RayCastInput, nodeId: number, userData: any, context: any)
  • Returns: number between 0 and 1 to continue search, 0 to terminate
context (any) User context passed to callback

b2DynamicTree_ShapeCast

Performs a shape cast query against nodes in a dynamic tree, testing for overlaps between a moving shape and static shapes in the tree.

b2DynamicTree_ShapeCast(tree: b2DynamicTree, input: b2ShapeCastInput, maskBits: number, callback: Function, context: any): void
Parameters
tree (b2DynamicTree) The dynamic tree to query against
input (b2ShapeCastInput) Contains the shape definition, translation vector, radius, and maximum fraction for the cast
maskBits (number) Bit mask to filter tree nodes by category
callback (Function) Function called when potential overlaps are found. Returns a fraction value to continue or terminate the cast
context (any) User data passed to the callback function
Returns
void: The callback function should have the signature: function(input: b2ShapeCastInput, nodeId: number, userData: any, context: any): number It should return 0 to terminate the cast, or a fraction between 0 and 1 to update the cast distance

b2DynamicTree_Rebuild

Rebuilds a dynamic tree by collecting all leaf nodes and reconstructing the tree structure. The function deallocates internal nodes during traversal and builds a new balanced tree from the collected leaf nodes.

b2DynamicTree_Rebuild(tree: b2DynamicTree): number
Parameters
tree (b2DynamicTree) The dynamic tree to rebuild
Returns
number: The number of leaf nodes in the rebuilt tree

b2DynamicTree

new b2DynamicTree()
Properties
nodes (Array<b2TreeNode>) : The tree nodes
root (number) : The root index
nodeCount (number) : The number of nodes
nodeCapacity (number) : The allocated node space
freeList (number) : Node free list
proxyCount (number) : Number of proxies created
leafIndices (Array<number>) : Leaf indices for rebuild
leafBoxes (Array<b2AABB>) : Leaf bounding boxes for rebuild
leafCenters (Array<b2Vec2>) : Leaf bounding box centers for rebuild
binIndices (Array<number>) : Bins for sorting during rebuild
rebuildCapacity (number) : Allocated space for rebuilding

Geometry

Geometry

Geometry

b2IsValidRay

Checks if a ray cast input is valid by verifying:

  • The origin vector is valid
  • The translation vector is valid
  • The maxFraction is a valid number
  • The maxFraction is between 0 and B2_HUGE(exclusive)
b2IsValidRay(input: b2RayCastInput): boolean
Parameters
input (b2RayCastInput) The ray cast input to validate, containing:
  • origin: b2Vec2 - Starting point of the ray
  • translation: b2Vec2 - Direction and length of the ray
  • maxFraction: number - Maximum fraction of translation to check
Returns
boolean: True if the ray cast input is valid, false otherwise.

b2MakePolygon

Creates a b2Polygon from a convex hull. If the hull has fewer than 3 points, returns a square shape. The function computes the polygon's vertices, edge normals, and centroid. Each edge normal is a unit vector perpendicular to the corresponding edge.

b2MakePolygon(hull: b2Hull, radius: number, forceCheck: boolean): b2Polygon
Parameters
hull (b2Hull) A convex hull structure containing points that define the polygon vertices
radius (number) The radius used to round the corners of the polygon
forceCheck (boolean = true) Whether to enforce hull validation
Returns
b2Polygon: A new polygon shape with computed vertices, normals, and centroid
Throws
  • Error: Throws an assertion error if the hull is invalid

b2MakeOffsetPolygon

Creates a polygon shape from a hull with specified radius and transform

b2MakeOffsetPolygon(hull: b2Hull, radius: number, transform: b2Transform, forceCheck: boolean): b2Polygon
Parameters
hull (b2Hull) The input hull to create the polygon from
radius (number) The radius to offset the polygon vertices
transform (b2Transform) Transform to apply to the hull points
forceCheck (boolean = true) Whether to force validation check of the hull
Returns
b2Polygon: A new polygon shape with transformed vertices, computed normals and centroid
Throws
  • Error: Throws assertion error if hull validation fails

b2MakeSquare

Creates a square polygon by calling b2MakeBox with equal dimensions. The square is centered at the origin with sides of length 2h.

b2MakeSquare(h: number): b2Polygon
Parameters
h (number) The half-width and half-height of the square.
Returns
b2Polygon: A polygon object representing a square centered at the origin.

b2MakeBox

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2MakeBox

b2MakeBox

Creates a rectangular polygon shape centered at the origin with specified half-widths. The vertices are arranged counter-clockwise starting from the bottom-left corner. The shape includes pre-computed normals for each edge.

b2MakeBox(hx: number, hy: number): b2Polygon
Parameters
hx (number) Half-width of the box in the x-direction (must be positive)
hy (number) Half-height of the box in the y-direction (must be positive)
Returns
b2Polygon: A polygon shape representing a rectangle with:
  • 4 vertices at (-hx,-hy), (hx,-hy), (hx,hy), (-hx,hy)
  • 4 normals pointing outward from each edge
  • radius of 0
  • centroid at (0,0)
Throws
  • Error: Throws an assertion error if hx or hy are not valid positive numbers

b2MakeRoundedBox

Creates a rounded box shape by generating a box with specified dimensions and corner radius.

b2MakeRoundedBox(hx: number, hy: number, radius: number): b2Polygon
Parameters
hx (number) Half-width of the box along the x-axis
hy (number) Half-height of the box along the y-axis
radius (number) Radius of the rounded corners
Returns
b2Polygon: A polygon shape representing a rounded box

b2MakeOffsetBox

Creates a b2Polygon representing a rectangle with the given dimensions. The box is centered at the specified position and rotated by the given angle. The resulting polygon includes 4 vertices, 4 normals, and has its centroid set to the center position.

b2MakeOffsetBox(hx: number, hy: number, center: b2Vec2, angle: number): b2Polygon
Parameters
hx (number) Half-width of the box along the x-axis
hy (number) Half-height of the box along the y-axis
center (b2Vec2) The center position of the box
angle (number) The rotation angle of the box in radians
Returns
b2Polygon: A polygon shape representing the box with 4 vertices and normals

b2TransformPolygon

Applies a rigid body transformation to a polygon by:

  1. Transforming each vertex using the full transform
  2. Rotating each normal vector using only the rotation component
  3. Transforming the centroid using the full transform
b2TransformPolygon(transform: b2Transform, polygon: b2Polygon): b2Polygon
Parameters
transform (b2Transform) The transformation to apply, consisting of a position vector and rotation.
polygon (b2Polygon) The polygon to transform, containing vertices, normals and centroid.
Returns
b2Polygon: The transformed polygon with updated vertices, normals and centroid.

b2ComputeCircleMass

Calculates the mass, center of mass, and rotational inertia for a circle shape with given density. The rotational inertia is computed about the center of mass using the parallel axis theorem when the circle's center is offset from the origin.

b2ComputeCircleMass(shape: b2Circle, density: number): b2MassData
Parameters
shape (b2Circle) A circle shape object containing radius and center properties
density (number) The density of the circle in mass per unit area
Returns
b2MassData: An object containing:
  • mass: The total mass of the circle
  • center: The center of mass (copied from shape.center)
  • rotationalInertia: The rotational inertia about the center of mass

b2ComputeCapsuleMass

Computes mass properties for a capsule shape, including total mass, center of mass, and rotational inertia. A capsule consists of a rectangle with semicircles at both ends.

b2ComputeCapsuleMass(shape: b2Capsule, density: number): b2MassData
Parameters
shape (b2Capsule) A capsule shape defined by two centers (center1, center2) and a radius
density (number) The density of the capsule in mass per unit area
Returns
b2MassData: An object containing:
  • mass: The total mass of the capsule
  • center: A b2Vec2 representing the center of mass
  • rotationalInertia: The moment of inertia about the center of mass

b2ComputePolygonMass

Computes mass properties for a polygon shape, including mass, center of mass, and rotational inertia. Handles special cases for 1-vertex (circle) and 2-vertex (capsule) polygons. For polygons with 3 or more vertices, calculates properties using triangulation.

b2ComputePolygonMass(shape: b2Polygon, density: number): b2MassData
Parameters
shape (b2Polygon) The polygon shape containing vertices, normals, count, and radius
density (number) The density of the shape in mass per unit area
Returns
b2MassData: Object containing:
  • mass: Total mass of the shape
  • center: Center of mass as b2Vec2
  • rotationalInertia: Moment of inertia about the center of mass
Throws
  • Error: Throws assertion error if shape.count is 0 or exceeds B2_MAX_POLYGON_VERTICES

b2ComputeCircleAABB

Calculates the AABB by transforming the circle's center point using the provided transform and extending the bounds by the circle's radius in each direction.

b2ComputeCircleAABB(shape: b2Circle, xf2: b2Transform): b2AABB
Parameters
shape (b2Circle) The circle shape containing center point and radius.
xf2 (b2Transform) The transform to be applied, consisting of a position (p) and rotation (q).
Returns
b2AABB: An AABB object defined by minimum and maximum points that bound the transformed circle.

b2ComputeCapsuleAABB

Calculates the minimum and maximum bounds of a capsule after applying a transform. The AABB is computed by transforming the capsule's center points and extending the bounds by the capsule's radius in all directions.

b2ComputeCapsuleAABB(shape: b2Capsule, xf2: b2Transform): b2AABB
Parameters
shape (b2Capsule) A capsule shape defined by two centers and a radius.
xf2 (b2Transform) A transform containing position and rotation to be applied to the capsule.
Returns
b2AABB: An AABB that encompasses the transformed capsule shape.

b2ComputePolygonAABB

Computes the Axis-Aligned Bounding Box (AABB) for a polygon shape after applying a transform. The AABB includes the polygon's radius in its calculations.

b2ComputePolygonAABB(shape: b2Polygon, xf2: b2Transform): b2AABB
Parameters
shape (b2Polygon) The polygon shape containing vertices and radius
xf2 (b2Transform) The transform to apply, consisting of position (p) and rotation (q)
Returns
b2AABB: An AABB object with lower and upper bounds that encompass the transformed polygon

b2ComputeSegmentAABB

Transforms the segment's endpoints using the provided transform, then creates an AABB that encompasses the transformed segment by finding the minimum and maximum coordinates of the transformed endpoints.

b2ComputeSegmentAABB(shape: b2Segment, xf2: b2Transform): b2AABB
Parameters
shape (b2Segment) A line segment defined by two points (point1 and point2)
xf2 (b2Transform) A transform containing position and rotation to be applied to the segment
Returns
b2AABB: An AABB that contains the transformed line segment

b2PointInCircle

Tests if a point lies within a circle by comparing the squared distance between the point and circle's center against the circle's squared radius.

b2PointInCircle(point: b2Vec2, shape: b2Circle): boolean
Parameters
point (b2Vec2) The point to test, represented as a 2D vector.
shape (b2Circle) The circle to test against, containing center and radius properties.
Returns
boolean: True if the point lies within or on the circle's boundary, false otherwise.

b2PointInCapsule

A capsule is defined by two end centers (center1 and center2) and a radius. The function calculates if the given point lies within the capsule by:

  1. Testing if the capsule has zero length (centers are identical)
  2. If not, finding the closest point on the line segment between centers
  3. Checking if the distance from the test point to the closest point is within the radius
b2PointInCapsule(point: b2Vec2, shape: b2Capsule): boolean
Parameters
point (b2Vec2) The point to test
shape (b2Capsule) The capsule shape defined by two centers and a radius
Returns
boolean: True if the point lies inside or on the capsule, false otherwise

b2PointInPolygon

Tests if a point lies inside a polygon shape by calculating the minimum distance between the point and the polygon.

b2PointInPolygon(point: b2Vec2, shape: b2Polygon): boolean
Parameters
point (b2Vec2) The point to test
shape (b2Polygon) The polygon shape to test against
Returns
boolean: True if the point is inside or on the polygon (within shape.radius), false otherwise

b2RayCastCircle

Calculates the intersection point between a ray and a circle shape. Returns early with no hit if the ray length is 0 or if the ray passes outside the circle radius.

b2RayCastCircle(input: b2RayCastInput, shape: b2Circle): b2CastOutput
Parameters
input (b2RayCastInput) The ray cast input parameters containing:
  • origin: b2Vec2 starting point of the ray
  • translation: b2Vec2 direction and length of the ray
  • maxFraction: number maximum intersection distance as a fraction of ray length
shape (b2Circle) The circle shape to test against, containing:
  • center: b2Vec2 position of circle center
  • radius: number radius of the circle
Returns
b2CastOutput: The ray cast results containing:
  • hit: boolean whether the ray intersects the circle
  • point: b2Vec2 point of intersection if hit is true
  • normal: b2Vec2 surface normal at intersection point if hit is true
  • fraction: number intersection distance as a fraction of ray length if hit is true

b2RayCastCapsule

Performs a ray cast against a capsule shape. A capsule is defined by two centers and a radius. If the capsule length is near zero, it degrades to a circle ray cast.

b2RayCastCapsule(input: b2RayCastInput, shape: b2Capsule): b2CastOutput
Parameters
input (b2RayCastInput) Contains ray cast parameters including:
  • origin: b2Vec2 starting point of the ray
  • translation: b2Vec2 direction and length of the ray
  • maxFraction: number maximum intersection distance as a fraction of ray length
shape (b2Capsule) The capsule to test against, containing:
  • center1: b2Vec2 first endpoint of capsule centerline
  • center2: b2Vec2 second endpoint of capsule centerline
  • radius: number radius of the capsule
Returns
b2CastOutput: Contains the ray cast results:
  • fraction: number intersection distance as a fraction of ray length
  • point: b2Vec2 point of intersection
  • normal: b2Vec2 surface normal at intersection
  • hit: boolean whether an intersection occurred

b2RayCastSegment

Performs a ray cast against a line segment, determining if and where the ray intersects the segment. For one-sided segments, intersections are only detected from one side based on a cross product test.

b2RayCastSegment(input: b2RayCastInput, shape: b2Segment, oneSided: boolean): b2CastOutput
Parameters
input (b2RayCastInput) Contains origin point, translation vector, and max fraction for the ray
shape (b2Segment) The line segment defined by two points (point1 and point2)
oneSided (boolean) Whether to treat the segment as one-sided
Returns
b2CastOutput: Contains hit status, intersection point, normal, and fraction along the ray

b2RayCastPolygon

Performs a ray cast against a polygon shape, detecting intersection points and normals. For non-zero radius polygons, converts the ray cast into a shape cast operation.

b2RayCastPolygon(input: b2RayCastInput, shape: b2Polygon): b2CastOutput
Parameters
input (b2RayCastInput) Contains origin point, translation vector, and max fraction
shape (b2Polygon) The polygon to test against, containing vertices, normals, count and radius
Returns
b2CastOutput: Contains:
  • hit: boolean indicating if intersection occurred
  • point: intersection point (if hit is true)
  • normal: surface normal at intersection (if hit is true)
  • fraction: fraction of translation where intersection occurred (if hit is true)
Throws
  • Error: Throws assertion error if input ray is invalid

b2ShapeCastCircle

Performs shape casting between a circle and a set of points with radius.

b2ShapeCastCircle(input: b2ShapeCastInput, shape: b2Circle): b2CastOutput
Parameters
input (b2ShapeCastInput) Contains points array, count, radius, translation and maxFraction
shape (b2Circle) Circle shape with center point and radius
Returns
b2CastOutput: The shape cast result containing intersection details

b2ShapeCastCapsule

Performs shape casting for a capsule shape against a set of points.

b2ShapeCastCapsule(input: b2ShapeCastInput, shape: b2Capsule): b2CastOutput
Parameters
input (b2ShapeCastInput) Contains the target points, count, radius, translation, and maxFraction for the shape cast
shape (b2Capsule) The capsule shape defined by two centers and a radius
Returns
b2CastOutput: The result of the shape cast operation

b2ShapeCastSegment

Performs a shape cast operation between a segment and another shape. The function creates proxies for both shapes, sets up their initial transforms, and performs the cast operation using the specified translation and maximum fraction.

b2ShapeCastSegment(input: b2ShapeCastInput, shape: b2Segment): b2CastOutput
Parameters
input (b2ShapeCastInput) Contains shape points, count, radius, translation, and maxFraction
shape (b2Segment) A segment defined by two points (point1 and point2)
Returns
b2CastOutput: The result of the shape cast operation

b2ShapeCastPolygon

Performs shape casting between a polygon shape and a set of points, checking for collisions along a translation path.

b2ShapeCastPolygon(input: b2ShapeCastInput, shape: b2Polygon): b2CastOutput
Parameters
input (b2ShapeCastInput) Contains the points, count, radius, translation, and maxFraction for the cast
shape (b2Polygon) The polygon shape to test against, containing vertices, count, and radius
Returns
b2CastOutput: The result of the shape cast operation

Hull

Hull

Hull

b2ComputeHull

Computes the convex hull of a set of 2D points. The function:

  • Filters duplicate points within a tolerance
  • Finds extreme points to establish initial hull edges
  • Recursively adds points to build the complete hull
  • Removes collinear/near-collinear points from final hull
b2ComputeHull(points: Array<b2Vec2>, count: number): b2Hull
Parameters
points (Array<b2Vec2>) Array of 2D points to compute hull from
count (number) Number of points in the array
Returns
b2Hull: A hull object containing the computed convex hull vertices
Throws
  • Error: If count < 3 or count > B2_MAX_POLYGON_VERTICES

b2ComputeHull

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2ComputeHull

b2ValidateHull

Validates that a hull meets the requirements for a valid convex polygon:

  • Has between 3 and B2_MAX_POLYGON_VERTICES points
  • Points are in counter-clockwise order
  • All points are behind the edges
  • No collinear points within b2_linearSlop tolerance
b2ValidateHull(hull: b2Hull): boolean
Parameters
hull (b2Hull) The hull to validate, containing points array and count
Returns
boolean: True if the hull is valid, false otherwise
Throws
  • Warning: Console warnings are issued explaining validation failures

Joint

Joint

Joint

b2DefaultDistanceJointDef

Creates and returns a new b2DistanceJointDef object initialized with specific default values. The length is set to 1 unit and the maxLength is set to B2_HUGE. All other properties of the joint definition retain their default values from the b2DistanceJointDef constructor.

b2DefaultDistanceJointDef(): b2DistanceJointDef
Returns
b2DistanceJointDef: A distance joint definition with:
  • length set to 1
  • maxLength set to B2_HUGE
  • all other properties at their default values

b2DefaultMotorJointDef

Initializes a new b2MotorJointDef with common default values. The joint definition includes preset values for maximum force, maximum torque, and correction factor while using default values for linear and angular offsets.

b2DefaultMotorJointDef(): b2MotorJointDef
Returns
b2MotorJointDef: A motor joint definition with:
  • maxForce: 1
  • maxTorque: 1
  • correctionFactor: 0.3
  • linearOffset: (0,0)
  • angularOffset: 0

b2DefaultMouseJointDef

Creates and returns a new b2MouseJointDef object initialized with default values for frequency (hertz), damping ratio, and maximum force parameters.

b2DefaultMouseJointDef(): b2MouseJointDef
Returns
b2MouseJointDef: A mouse joint definition with:
  • hertz = 4
  • dampingRatio = 1
  • maxForce = 1

b2DefaultPrismaticJointDef

Creates and returns a new b2PrismaticJointDef instance with localAxisA initialized to a unit vector pointing along the x-axis (1,0). All other properties retain their default values from the b2PrismaticJointDef constructor.

b2DefaultPrismaticJointDef(): b2PrismaticJointDef
Returns
b2PrismaticJointDef: A prismatic joint definition with localAxisA set to (1,0)

b2DefaultRevoluteJointDef

Creates and initializes a new b2RevoluteJointDef with default values. Sets the drawSize property to 0.25 for visualization purposes.

b2DefaultRevoluteJointDef(): b2RevoluteJointDef
Returns
b2RevoluteJointDef: A new revolution joint definition with drawSize set to 0.25

b2DefaultWeldJointDef

Creates and returns a new b2WeldJointDef object initialized with default values. A weld joint essentially glues two bodies together at a reference point.

b2DefaultWeldJointDef(): b2WeldJointDef
Returns
b2WeldJointDef: A new weld joint definition with default configuration:
  • localAnchorA: b2Vec2(0,0)
  • localAnchorB: b2Vec2(0,0)
  • referenceAngle: 0
  • stiffness: 0
  • damping: 0

b2DefaultWheelJointDef

Creates and returns a new b2WheelJointDef with common default values. The joint's local axis is set to point upward, and spring behavior is enabled with standard frequency and damping values.

b2DefaultWheelJointDef(): b2WheelJointDef
Returns
b2WheelJointDef: A wheel joint definition with:
  • localAxisA set to (0,1)
  • enableSpring set to true
  • hertz set to 1
  • dampingRatio set to 0.7

b2CreateDistanceJoint

b2CreateDistanceJoint(worldId: b2WorldId, def: b2DistanceJointDef): b2JointId
Parameters
worldId (b2WorldId) The ID of the Box2D world
def (b2DistanceJointDef) The joint definition containing:
  • bodyIdA: ID of the first body
  • bodyIdB: ID of the second body
  • localAnchorA: Local anchor point on body A
  • localAnchorB: Local anchor point on body B
  • length: Desired distance between anchor points
  • minLength: Minimum allowed distance
  • maxLength: Maximum allowed distance
  • hertz: Spring frequency in Hz
  • dampingRatio: Spring damping ratio
  • maxMotorForce: Maximum motor force
  • motorSpeed: Motor speed
  • enableSpring: Enable/disable spring
  • enableLimit: Enable/disable length limits
  • enableMotor: Enable/disable motor
  • collideConnected: Allow collision between connected bodies
  • userData: User data
Returns
b2JointId: The ID of the created distance joint
Throws
  • Error: Throws assertion error if world is locked, bodies are invalid, or length <= 0

b2CreateMotorJoint

b2CreateMotorJoint(worldId: b2WorldId, def: b2MotorJointDef): b2JointId
Parameters
worldId (b2WorldId) The ID of the Box2D world
def (b2MotorJointDef) The joint definition containing:
  • bodyIdA: ID of the first body
  • bodyIdB: ID of the second body
  • linearOffset: The target linear offset between bodies
  • angularOffset: The target angular offset between bodies
  • maxForce: Maximum force that can be applied
  • maxTorque: Maximum torque that can be applied
  • correctionFactor: Position correction factor in [0,1]
  • collideConnected: Whether bodies can collide
  • userData: User data
Returns
b2JointId: The ID of the created motor joint
Throws
  • Error: If the world is locked when attempting to create the joint

b2CreateMouseJoint

Creates a mouse joint between two bodies at a specified target point. The joint transforms the target point into local coordinates for both bodies and initializes the joint properties including frequency, damping ratio, and maximum force.

b2CreateMouseJoint(worldId: b2WorldId, def: b2MouseJointDef): b2JointId
Parameters
worldId (b2WorldId) The ID of the Box2D world where the joint will be created
def (b2MouseJointDef) The mouse joint definition containing:
  • bodyIdA: ID of the first body
  • bodyIdB: ID of the second body
  • target: Target point in world coordinates
  • hertz: Frequency in Hertz
  • dampingRatio: Damping ratio
  • maxForce: Maximum force
  • userData: User data
  • collideConnected: Whether connected bodies can collide
Returns
b2JointId: The ID of the created mouse joint
Throws
  • Error: Throws an assertion error if the world is locked

b2CreateRevoluteJoint

b2CreateRevoluteJoint(worldId: b2WorldId, def: b2RevoluteJointDef): b2JointId
Parameters
worldId (b2WorldId) The ID of the Box2D world
def (b2RevoluteJointDef) The joint definition containing properties like:
  • bodyIdA: ID of first body
  • bodyIdB: ID of second body
  • localAnchorA: Local anchor point on body A
  • localAnchorB: Local anchor point on body B
  • referenceAngle: Initial angle between bodies (clamped to [-Ï€,Ï€])
  • hertz: Spring frequency
  • dampingRatio: Spring damping ratio
  • lowerAngle: Lower angle limit (clamped to [-Ï€,Ï€])
  • upperAngle: Upper angle limit (clamped to [-Ï€,Ï€])
  • maxMotorTorque: Maximum motor torque
  • motorSpeed: Motor speed
  • enableSpring: Enable spring behavior
  • enableLimit: Enable angle limits
  • enableMotor: Enable motor
  • collideConnected: Allow collision between connected bodies
  • userData: User data
  • drawSize: Drawing size
Returns
b2JointId: ID of the created revolute joint
Throws
  • Error: If the world is locked

b2CreatePrismaticJoint

Creates a prismatic joint between two bodies in a Box2D world. A prismatic joint constrains two bodies to move relative to each other along a specified axis.

b2CreatePrismaticJoint(worldId: b2WorldId, def: b2PrismaticJointDef): b2JointId
Parameters
worldId (b2WorldId) The identifier of the Box2D world
def (b2PrismaticJointDef) The joint definition containing:
  • bodyIdA: First body ID
  • bodyIdB: Second body ID
  • localAnchorA: Anchor point on body A in local coordinates
  • localAnchorB: Anchor point on body B in local coordinates
  • localAxisA: The axis of translation in body A's local coordinates
  • referenceAngle: The initial angle between the bodies
  • enableLimit: Whether translation limits are enabled
  • lowerTranslation: Lower translation limit
  • upperTranslation: Upper translation limit
  • enableMotor: Whether the motor is enabled
  • motorSpeed: Motor speed
  • maxMotorForce: Maximum motor force
  • enableSpring: Whether spring is enabled
  • hertz: Spring frequency in Hz
  • dampingRatio: Spring damping ratio
  • collideConnected: Whether connected bodies can collide
  • userData: User data
Returns
b2JointId: The identifier for the created prismatic joint

b2CreateWeldJoint

Creates a weld joint between two bodies in a Box2D world.

b2CreateWeldJoint(worldId: b2WorldId, def: b2WeldJointDef): b2JointId
Parameters
worldId (b2WorldId) The identifier of the Box2D world
def (b2WeldJointDef) The weld joint definition containing:
  • bodyIdA: ID of the first body
  • bodyIdB: ID of the second body
  • localAnchorA: Local anchor point on body A
  • localAnchorB: Local anchor point on body B
  • referenceAngle: Reference angle between the bodies
  • linearHertz: Frequency for the linear constraint
  • linearDampingRatio: Damping ratio for the linear constraint
  • angularHertz: Frequency for the angular constraint
  • angularDampingRatio: Damping ratio for the angular constraint
  • collideConnected: Whether the connected bodies can collide
  • userData: User data associated with the joint
Returns
b2JointId: The identifier of the created weld joint
Throws
  • Error: Throws an assertion error if the world is locked

b2CreateWheelJoint

Creates a wheel joint between two bodies in a Box2D world. A wheel joint provides two degrees of freedom: translation along a specified axis and rotation about an orthogonal axis. The joint can be configured with a spring and damper mechanism, translation limits, and a motor.

b2CreateWheelJoint(worldId: b2WorldId, def: b2WheelJointDef): b2JointId
Parameters
worldId (b2WorldId) The identifier of the Box2D world
def (b2WheelJointDef) The wheel joint definition containing configuration parameters
Returns
b2JointId: The identifier of the created wheel joint
Throws
  • Error: Throws an assertion error if the world is locked

b2DestroyJoint

Destroys a joint in the physics world. If the world is locked (e.g. during collision detection or integration), the function will return without destroying the joint. The function internally calls b2DestroyJointInternal to handle the actual joint destruction.

b2DestroyJoint(jointId: b2JointId): void
Parameters
jointId (b2JointId) The identifier of the joint to be destroyed
Returns
void:
Throws
  • Error: Throws an assertion error if attempting to destroy a joint in a locked world

b2Joint_GetType

Retrieves the joint type from the world using the provided joint ID. The function first gets the world reference from the joint ID, then retrieves the full joint object to access its type property.

b2Joint_GetType(jointId: b2JointId): b2JointType
Parameters
jointId (b2JointId) The ID of the joint to query.
Returns
b2JointType: The type of the specified joint.

b2Joint_GetBodyA

This function retrieves the identifier of the first body (body A) that is connected to the specified joint. The joint must exist in the world referenced by the jointId.

b2Joint_GetBodyA(jointId: b2JointId): b2BodyId
Parameters
jointId (b2JointId) The identifier of the joint.
Returns
b2BodyId: The identifier of the first body connected to the joint.

b2Joint_GetBodyB

This function retrieves the identifier of the second body (body B) that is connected to the specified joint. The joint must exist in the world referenced by the jointId.

b2Joint_GetBodyB(jointId: b2JointId): b2BodyId
Parameters
jointId (b2JointId) The identifier of the joint.
Returns
b2BodyId: The identifier of body B connected to the joint.

b2Joint_GetLocalAnchorA

Retrieves the local anchor point A from a joint's simulation data. The anchor point is expressed in the local coordinate system of body A.

b2Joint_GetLocalAnchorA(jointId: b2JointId): b2Vec2
Parameters
jointId (b2JointId) The identifier for the joint.
Returns
b2Vec2: The local anchor point A in the body A frame.

b2Joint_GetLocalAnchorB

Retrieves the local anchor point B of a joint, which represents the connection point on the second body (body B) in that body's local coordinate system.

b2Joint_GetLocalAnchorB(jointId: b2JointId): b2Vec2
Parameters
jointId (b2JointId) The identifier for the joint.
Returns
b2Vec2: The local anchor point B in the body's local coordinates.

b2Joint_SetCollideConnected

When enabled, the bodies connected by the joint can collide with each other. When disabled, collisions between the connected bodies are filtered out. The function updates the broadphase when enabling collisions and destroys existing contacts between the bodies when disabling collisions.

b2Joint_SetCollideConnected(jointId: b2JointId, shouldCollide: boolean): void
Parameters
jointId (b2JointId) The identifier for the joint to modify.
shouldCollide (boolean) True to enable collision between connected bodies, false to disable.
Returns
void:

b2Joint_GetCollideConnected

Gets the collideConnected flag for the specified joint. This flag determines if the two bodies connected by this joint are allowed to collide with each other.

b2Joint_GetCollideConnected(jointId: b2JointId): boolean
Parameters
jointId (b2JointId) The ID of the joint to query
Returns
boolean: Whether the connected bodies can collide with each other

b2Joint_SetUserData

Associates arbitrary user data with a specified joint in the physics world. The joint is located using its world and joint identifiers, and its user data property is updated with the provided value.

b2Joint_SetUserData(jointId: b2JointId, userData: any): void
Parameters
jointId (b2JointId) The identifier for the joint to modify.
userData (any) The user data to associate with the joint.
Returns
void:

b2Joint_GetUserData

Retrieves the user data that was previously attached to the specified joint. The function first gets the world object from the joint ID, then retrieves the joint using the full joint ID, and finally returns the userData property of that joint.

b2Joint_GetUserData(jointId: b2JointId): void
Parameters
jointId (b2JointId) The identifier for the joint.
Returns
void: The user data associated with the joint.

b2Joint_WakeBodies

Wakes up both bodies connected by a joint in the physics simulation.

b2Joint_WakeBodies(jointId: b2JointId): void
Parameters
jointId (b2JointId) The identifier for the joint whose connected bodies should be awakened.
Returns
void:
Throws
  • Error: If the world reference in the jointId is invalid or cannot be accessed.

b2Joint_GetConstraintForce

Returns the constraint force for different joint types including distance, motor, mouse, prismatic, revolute, weld, and wheel joints. The force is retrieved from the corresponding joint-specific force getter function.

b2Joint_GetConstraintForce(jointId: b2JointId): b2Vec2
Parameters
jointId (b2JointId) The identifier for the joint.
Returns
b2Vec2: The constraint force vector. Returns (0,0) for unknown joint types.
Throws
  • Error: Throws an assertion error for unknown joint types.

b2Joint_GetConstraintTorque

Returns the constraint torque for different joint types including motor, mouse, prismatic, revolute, weld and wheel joints. For distance joints, it always returns 0.

b2Joint_GetConstraintTorque(jointId: b2JointId): number
Parameters
jointId (b2JointId) The ID of the joint to get the constraint torque from.
Returns
number: The constraint torque value. Returns 0 for distance joints or if joint type is invalid.
Throws
  • Error: Throws an assertion error if an unsupported joint type is provided.

Manifold

Manifold

Manifold

b2CollideCircles

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2CollideCircles

b2CollideCircles

Computes collision information between two circles transformed by their respective transforms.

b2CollideCircles(circleA: b2Circle, xfA: b2Transform, circleB: b2Circle, xfB: b2Transform, manifold: b2Manifold): b2Manifold
Parameters
circleA (b2Circle) The first circle
xfA (b2Transform) Transform for the first circle
circleB (b2Circle) The second circle
xfB (b2Transform) Transform for the second circle
manifold (b2Manifold) The output collision manifold
Returns
b2Manifold: The collision manifold containing contact points, normal, and separation information. If no collision is detected, returns a cleared manifold.

b2CollideCapsuleAndCircle

Computes collision information between a capsule shape and a circle shape.

b2CollideCapsuleAndCircle(capsuleA: b2Capsule, xfA: b2Transform, circleB: b2Circle, xfB: b2Transform, manifold: b2Manifold): b2Manifold
Parameters
capsuleA (b2Capsule) The capsule shape A with properties center1, center2, and radius
xfA (b2Transform) Transform for shape A containing position (p) and rotation (q)
circleB (b2Circle) The circle shape B with properties center and radius
xfB (b2Transform) Transform for shape B containing position (p) and rotation (q)
manifold (b2Manifold) Output collision manifold to be populated
Returns
b2Manifold: The populated collision manifold containing contact points, normal, separation, and other collision data

b2CollidePolygonAndCircle

Computes collision information between a polygon and a circle.

b2CollidePolygonAndCircle(polygonA: b2Polygon, xfA: b2Transform, circleB: b2Circle, xfB: b2Transform, manifold: b2Manifold): b2Manifold
Parameters
polygonA (b2Polygon) The polygon shape
xfA (b2Transform) Transform for polygon A
circleB (b2Circle) The circle shape
xfB (b2Transform) Transform for circle B
manifold (b2Manifold) Output collision manifold
Returns
b2Manifold: The collision manifold containing contact points, normal, and separation

b2CollideCapsules

Computes the collision manifold between two capsule shapes in 2D space. A capsule is defined by two endpoints and a radius.

b2CollideCapsules(capsuleA: b2Capsule, xfA: b2Transform, capsuleB: b2Capsule, xfB: b2Transform, manifold: b2Manifold): void
Parameters
capsuleA (b2Capsule) The first capsule shape
xfA (b2Transform) Transform for the first capsule
capsuleB (b2Capsule) The second capsule shape
xfB (b2Transform) Transform for the second capsule
manifold (b2Manifold) Output collision manifold
Returns
void: Modifies the manifold parameter with collision data:
  • normalX/Y: Collision normal vector
  • pointCount: Number of contact points (0-2)
  • points[]: Contact point data including:
  • anchorA/B: Contact points in local coordinates
  • separation: Penetration depth
  • id: Contact ID

b2CollideSegmentAndCapsule

Converts the segment to a zero-radius capsule and delegates to b2CollideCapsules for the actual collision computation.

b2CollideSegmentAndCapsule(segmentA: b2Segment, xfA: b2Transform, capsuleB: b2Capsule, xfB: b2Transform): b2Manifold
Parameters
segmentA (b2Segment) A line segment defined by two points (point1, point2)
xfA (b2Transform) Transform for segmentA containing position and rotation
capsuleB (b2Capsule) A capsule shape defined by two points and a radius
xfB (b2Transform) Transform for capsuleB containing position and rotation
Returns
b2Manifold: Collision manifold containing contact points and normal

b2CollidePolygonAndCapsule

Computes collision manifold between a polygon and a capsule by converting the capsule to a polygon and using polygon-polygon collision detection.

b2CollidePolygonAndCapsule(polygonA: b2Polygon, xfA: b2Transform, capsuleB: b2Capsule, xfB: b2Transform, manifold: b2Manifold): b2Manifold
Parameters
polygonA (b2Polygon) The first collision shape (polygon)
xfA (b2Transform) Transform for polygon A, containing position and rotation
capsuleB (b2Capsule) The second collision shape (capsule) defined by two centers and a radius
xfB (b2Transform) Transform for capsule B, containing position and rotation
manifold (b2Manifold) The output collision manifold to be populated
Returns
b2Manifold: The collision manifold containing contact points and normal

b2CollidePolygons

Detects collision between two polygons and generates contact information. Transforms the polygons into a common frame, finds the separating axes, and generates contact points. The manifold includes contact points with anchor positions, separation distance, contact IDs and collision normal.

b2CollidePolygons(polygonA: b2Polygon, xfA: b2Transform, polygonB: b2Polygon, xfB: b2Transform, manifold: b2Manifold): b2Manifold
Parameters
polygonA (b2Polygon) First polygon
xfA (b2Transform) Transform for first polygon containing position (p) and rotation (q)
polygonB (b2Polygon) Second polygon
xfB (b2Transform) Transform for second polygon containing position (p) and rotation (q)
manifold (b2Manifold) Output manifold to store collision data
Returns
b2Manifold: The collision manifold containing contact points, normal and separation

b2CollideSegmentAndCircle

Computes collision detection between a line segment and a circle by converting the segment to a zero-radius capsule and using capsule-circle collision.

b2CollideSegmentAndCircle(segmentA: b2Segment, xfA: b2Transform, circleB: b2Circle, xfB: b2Transform, manifold: b2Manifold): b2Manifold
Parameters
segmentA (b2Segment) The line segment shape
xfA (b2Transform) Transform for segmentA
circleB (b2Circle) The circle shape
xfB (b2Transform) Transform for circleB
manifold (b2Manifold) The collision manifold to populate
Returns
b2Manifold: The collision manifold containing contact information

b2CollideSegmentAndPolygon

Computes collision manifold between a line segment and a polygon by converting the segment into a zero-width capsule and using polygon collision detection.

b2CollideSegmentAndPolygon(segmentA: b2Segment, xfA: b2Transform, polygonB: b2Polygon, xfB: b2Transform, manifold: b2Manifold): b2Manifold
Parameters
segmentA (b2Segment) The line segment
xfA (b2Transform) Transform for segmentA
polygonB (b2Polygon) The polygon to test collision against
xfB (b2Transform) Transform for polygonB
manifold (b2Manifold) The manifold to populate with collision data
Returns
b2Manifold: Collision manifold containing contact points and normal

b2CollideChainSegmentAndCircle

Computes collision detection between a chain segment and a circle.

b2CollideChainSegmentAndCircle(chainSegmentA: Object, xfA: Object, circleB: Object, xfB: Object, manifold: Object): Object
Parameters
chainSegmentA (Object) A chain segment with properties segment (containing point1 and point2) and ghost points (ghost1, ghost2)
xfA (Object) Transform for chain segment containing position (p) and rotation (q)
circleB (Object) Circle object with center point and radius
xfB (Object) Transform for circle containing position (p) and rotation (q)
manifold (Object) Contact manifold to store collision results
Returns
Object: The manifold object containing collision data:
  • normalX/Y: collision normal in world coordinates
  • points: array with contact point data including:
  • anchorA/B: contact points in local coordinates
  • point: contact point in world coordinates
  • separation: distance between shapes
  • id: contact ID
  • pointCount: number of contact points

b2CollideChainSegmentAndCapsule

Computes collision between a chain segment and a capsule by converting the capsule to a polygon and delegating to the segment-polygon collision function.

b2CollideChainSegmentAndCapsule(segmentA: b2ChainSegment, xfA: b2Transform, capsuleB: b2Capsule, xfB: b2Transform, cache: b2SimplexCache, manifold: b2Manifold): void
Parameters
segmentA (b2ChainSegment) The chain segment shape
xfA (b2Transform) Transform for segmentA
capsuleB (b2Capsule) The capsule shape defined by two centers and a radius
xfB (b2Transform) Transform for capsuleB
cache (b2SimplexCache) Simplex cache for persistent contact information
manifold (b2Manifold) Contact manifold to store collision results
Returns
void:

b2CollideChainSegmentAndPolygon

Computes the collision manifold between a chain segment (a segment with rounded corners) and a polygon. The function handles edge cases including convex/concave corners and determines contact points and normals. The manifold is populated with contact points and can contain 0, 1 or 2 contact points depending on the collision configuration.

b2CollideChainSegmentAndPolygon(chainSegmentA: b2ChainSegment, xfA: b2Transform, polygonB: b2Polygon, xfB: b2Transform, cache: b2DistanceCache, manifold: b2Manifold): b2Manifold
Parameters
chainSegmentA (b2ChainSegment) The chain segment shape A
xfA (b2Transform) Transform for shape A
polygonB (b2Polygon) The polygon shape B
xfB (b2Transform) Transform for shape B
cache (b2DistanceCache) Cache for distance calculations
manifold (b2Manifold) The contact manifold to populate
Returns
b2Manifold: The populated contact manifold

MathFunctions

MathFunctions

MathFunctions

b2GetLengthAndNormalize

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2GetLengthAndNormalize

b2GetLengthAndNormalize

Calculates the length of a vector and returns its normalized form.

b2GetLengthAndNormalize(v: b2Vec2): {length: number, normal: b2Vec2}
Parameters
v (b2Vec2) The input vector to normalize
Returns
{length: number, normal: b2Vec2}: An object containing:
  • length: The original length of the vector
  • normal: A normalized vector (unit length) in the same direction as v. Returns (0,0) if the input vector length is below epsilon

b2Vec2

new b2Vec2()
Properties
x (number) : x coordinate
y (number) : y coordinate

b2Rot

new b2Rot()
Properties
s (number) : The sine component of the rotation
c (number) : The cosine component of the rotation

b2Rot

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Rot

b2Rot

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Rot

b2Transform

new b2Transform()
Properties
p (b2Vec2) : Position vector
q (b2Rot) : Rotation component

b2Mat22

new b2Mat22()
Properties
cy (b2Vec2) : Matrix columns

b2Mat22

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Mat22

b2AABB

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2AABB

b2AABB

new b2AABB()
Properties
lowerBound (b2Vec2) : The lower vertex of the bounding box
upperBound (b2Vec2) : The upper vertex of the bounding box

b2AABB

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2AABB

b2AABB

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2AABB

b2MinFloat

b2MinFloat(a: number, b: number): number
Parameters
a (number) First number to compare
b (number) Second number to compare
Returns
number: The smaller of the two input numbers

b2MinFloat

FUNCTIONS

b2MinFloat

b2MinFloat

FUNCTIONS

b2MinFloat

b2MaxFloat

b2MaxFloat(a: number, b: number): number
Parameters
a (number) First number to compare
b (number) Second number to compare
Returns
number: The maximum value between a and b

b2AbsFloat

An implementation of absolute value that returns the positive magnitude of the input number.

b2AbsFloat(a: number): number
Parameters
a (number) The input number
Returns
number: The absolute value of the input

b2ClampFloat

Returns lower if a < lower, upper if a > upper, otherwise returns a.

b2ClampFloat(a: number, lower: number, upper: number): number
Parameters
a (number) The value to clamp
lower (number) The lower bound
upper (number) The upper bound
Returns
number: The clamped value between lower and upper bounds

b2MinInt

A comparison function that returns the minimum value between two integers using a ternary operator.

b2MinInt(a: number, b: number): number
Parameters
a (number) First integer to compare
b (number) Second integer to compare
Returns
number: The smaller of the two input integers

b2MaxInt

b2MaxInt(a: number, b: number): number
Parameters
a (number) First integer to compare
b (number) Second integer to compare
Returns
number: The larger of the two input integers

b2AbsInt

Computes the absolute value of an integer using conditional logic rather than Math.abs().

b2AbsInt(a: number): number
Parameters
a (number) The integer input value.
Returns
number: The absolute value of the input.

b2ClampInt

Returns lower if a < lower, upper if a > upper, otherwise returns a.

b2ClampInt(a: number, lower: number, upper: number): number
Parameters
a (number) The integer value to clamp
lower (number) The lower bound (inclusive)
upper (number) The upper bound (inclusive)
Returns
number: The clamped integer value

b2Dot

Computes the dot product (scalar product) of two 2D vectors using the formula: dot = a.x * b.x + a.y * b.y

b2Dot(a: b2Vec2, b: b2Vec2): number
Parameters
a (b2Vec2) First 2D vector.
b (b2Vec2) Second 2D vector.
Returns
number: The dot product of vectors a and b.

b2Cross

Calculates the cross product between two 2D vectors, which represents the signed area of the parallelogram formed by these vectors.

b2Cross(a: b2Vec2, b: b2Vec2): number
Parameters
a (b2Vec2) The first 2D vector
b (b2Vec2) The second 2D vector
Returns
number: The cross product (a.x * b.y - a.y * b.x)

b2CrossVS

Computes the cross product of a vector and scalar, returning a new vector that is perpendicular to the input vector and scaled by the scalar value.

b2CrossVS(v: b2Vec2, s: number): b2Vec2
Parameters
v (b2Vec2) The input vector
s (number) The scalar value
Returns
b2Vec2: A new vector where x = s * v.y and y = -s * v.x

b2CrossSV

Computes s × v, where × denotes the cross product. The result is a new vector (-s * v.y, s * v.x).

b2CrossSV(s: number, v: b2Vec2): b2Vec2
Parameters
s (number) The scalar value
v (b2Vec2) The 2D vector
Returns
b2Vec2: A new vector perpendicular to the input vector, scaled by s

b2LeftPerp

Creates a new vector that is perpendicular to the input vector by rotating it 90 degrees counter-clockwise. The new vector is computed by setting the x component to the negative y component of the input, and the y component to the x component of the input.

b2LeftPerp(v: b2Vec2): b2Vec2
Parameters
v (b2Vec2) The input vector to rotate.
Returns
b2Vec2: A new vector perpendicular to the input, rotated 90 degrees counter-clockwise.

b2RightPerp

Creates a new vector that is perpendicular (rotated 90 degrees clockwise) to the input vector. For a vector (x,y), returns (y,-x).

b2RightPerp(v: b2Vec2): b2Vec2
Parameters
v (b2Vec2) The input vector to rotate.
Returns
b2Vec2: A new vector perpendicular to the input, rotated 90 degrees clockwise.

b2Add

Creates a new b2Vec2 where the x and y components are the sums of the corresponding components of the input vectors.

b2Add(a: b2Vec2, b: b2Vec2): b2Vec2
Parameters
a (b2Vec2) The first vector.
b (b2Vec2) The second vector.
Returns
b2Vec2: A new vector representing the sum of the input vectors (a + b).

b2Add

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Add

b2Add

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Add

b2Add

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Add

b2Add

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Add

b2Add

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Add

b2Add

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Add

b2Sub

Creates a new 2D vector by subtracting the components of vector b from vector a. The resulting vector has coordinates (a.x - b.x, a.y - b.y).

b2Sub(a: b2Vec2, b: b2Vec2): b2Vec2
Parameters
a (b2Vec2) The first vector.
b (b2Vec2) The second vector.
Returns
b2Vec2: A new vector representing (a - b).

b2Neg

Creates a new b2Vec2 with the negated x and y components of the input vector.

b2Neg(a: b2Vec2): b2Vec2
Parameters
a (b2Vec2) The input vector to negate.
Returns
b2Vec2: A new vector with components (-a.x, -a.y).

b2Lerp

Calculates a point that lies on the straight line between vectors a and b, where t=0 returns a, t=1 returns b, and values in between return proportionally interpolated points.

b2Lerp(a: b2Vec2, b: b2Vec2, t: number): b2Vec2
Parameters
a (b2Vec2) The starting vector
b (b2Vec2) The ending vector
t (number) The interpolation parameter between 0 and 1
Returns
b2Vec2: A new vector representing the interpolated point

b2Mul

Multiplies the x components of both vectors together and the y components of both vectors together, returning a new b2Vec2 with these products as its components.

b2Mul(a: b2Vec2, b: b2Vec2): b2Vec2
Parameters
a (b2Vec2) First 2D vector with x and y components.
b (b2Vec2) Second 2D vector with x and y components.
Returns
b2Vec2: A new vector where each component is the product of the corresponding components of a and b.

b2MulSV

Performs scalar multiplication on a 2D vector, where each component of the vector is multiplied by the scalar value.

b2MulSV(s: number, v: b2Vec2): b2Vec2
Parameters
s (number) The scalar value to multiply with the vector.
v (b2Vec2) The 2D vector to be multiplied.
Returns
b2Vec2: A new b2Vec2 representing the scaled vector (s * v).

b2MulAdd

b2MulAdd(a: b2Vec2, s: number, b: b2Vec2): b2Vec2
Parameters
a (b2Vec2) First vector operand
s (number) Scalar multiplier
b (b2Vec2) Second vector operand
Returns
b2Vec2: A new vector representing the result of a + s * b

b2MulSub

b2MulSub(a: b2Vec2, s: number, b: b2Vec2): b2Vec2
Parameters
a (b2Vec2) The first vector operand
s (number) The scalar multiplier
b (b2Vec2) The second vector operand
Returns
b2Vec2: A new vector representing the result of a - s * b

b2Abs

Returns a new b2Vec2 with the absolute values of the input vector's components.

b2Abs(a: b2Vec2): b2Vec2
Parameters
a (b2Vec2) The input vector whose components will be converted to absolute values.
Returns
b2Vec2: A new vector containing the absolute values of the input vector's x and y components.

b2Min

b2Min(a: b2Vec2, b: b2Vec2): b2Vec2
Parameters
a (b2Vec2) First 2D vector
b (b2Vec2) Second 2D vector
Returns
b2Vec2: A new vector with x = min(a.x, b.x) and y = min(a.y, b.y)

b2Max

Creates a new b2Vec2 where:

  • x component is the maximum of a.x and b.x
  • y component is the maximum of a.y and b.y
b2Max(a: b2Vec2, b: b2Vec2): b2Vec2
Parameters
a (b2Vec2) First input vector
b (b2Vec2) Second input vector
Returns
b2Vec2: A new vector where each component is the maximum of the corresponding components from vectors a and b

b2Clamp

Creates a new 2D vector where each component (x,y) is clamped between the corresponding components of vectors a and b. Uses b2ClampFloat internally to clamp individual components.

b2Clamp(v: b2Vec2, a: b2Vec2, b: b2Vec2): b2Vec2
Parameters
v (b2Vec2) The vector to clamp
a (b2Vec2) The minimum bounds vector
b (b2Vec2) The maximum bounds vector
Returns
b2Vec2: A new vector with components clamped between a and b

b2Length

Computes the Euclidean length of a 2D vector using the formula sqrt(x² + y²).

b2Length(v: b2Vec2): number
Parameters
v (b2Vec2) A 2D vector with x and y components.
Returns
number: The scalar length of the vector.

b2LengthSquared

Computes the dot product of a vector with itself, which gives the squared length of the vector without performing a square root operation.

b2LengthSquared(v: b2Vec2): number
Parameters
v (b2Vec2) A 2D vector with x and y components.
Returns
number: The squared length of the vector (x² + y²).

b2Distance

Computes the straight-line distance between two points using the Pythagorean theorem.

b2Distance(a: b2Vec2, b: b2Vec2): number
Parameters
a (b2Vec2) The first 2D vector point
b (b2Vec2) The second 2D vector point
Returns
number: The distance between points a and b

b2DistanceSquared

Computes the squared Euclidean distance between two points without taking the square root. The calculation is (b.x - a.x)² + (b.y - a.y)²

b2DistanceSquared(a: b2Vec2, b: b2Vec2): number
Parameters
a (b2Vec2) The first 2D vector point
b (b2Vec2) The second 2D vector point
Returns
number: The squared distance between points a and b

b2MakeRot

Constructs a b2Rot object by computing the cosine and sine of the provided angle. The resulting b2Rot contains these values as its 'c' and 's' components respectively.

b2MakeRot(angle: number): b2Rot
Parameters
angle (number) The rotation angle in radians
Returns
b2Rot: A new b2Rot object containing the cosine and sine of the input angle

b2NormalizeRot

Computes the magnitude of the rotation vector and divides both components by it to create a normalized rotation. If the magnitude is 0, returns a default rotation.

b2NormalizeRot(q: b2Rot): b2Rot
Parameters
q (b2Rot) A rotation object containing cosine (c) and sine (s) components
Returns
b2Rot: A new normalized b2Rot object where the components form a unit vector

b2IsNormalized

Verifies that the sum of squares of the sine and cosine components equals 1 within a tolerance of ±6e-4, which indicates a valid rotation.

b2IsNormalized(q: b2Rot): boolean
Parameters
q (b2Rot) A rotation object containing sine (s) and cosine (c) components
Returns
boolean: True if the rotation is normalized within a tolerance of 6e-4

b2IsNormalized

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2IsNormalized

b2NLerp

Linearly interpolates between two rotations and normalizes the result. When t=0 returns q12, when t=1 returns q22.

b2NLerp(q1: b2Rot, q2: b2Rot, t: number): b2Rot
Parameters
q1 (b2Rot) The first rotation
q2 (b2Rot) The second rotation
t (number) Interpolation factor between 0 and 1
Returns
b2Rot: The normalized interpolated rotation

b2IntegrateRotation

Performs rotation integration while ensuring the resulting rotation remains normalized through magnitude scaling. The function handles the case where magnitude could be zero by returning a default rotation.

b2IntegrateRotation(q1: b2Rot, deltaAngle: number): b2Rot
Parameters
q1 (b2Rot) The initial rotation.
deltaAngle (number) The angle to rotate by, in radians.
Returns
b2Rot: A new normalized rotation after applying the integration.

b2ComputeAngularVelocity

Calculates the angular velocity by comparing two rotations and dividing by the time step. Uses the formula (θ2 - θ1)/dt where θ is extracted from the rotations using their sine and cosine components.

b2ComputeAngularVelocity(q1: b2Rot, q2: b2Rot, inv_h: number): number
Parameters
q1 (b2Rot) The first rotation
q2 (b2Rot) The second rotation
inv_h (number) The inverse of the time step (1/dt)
Returns
number: The computed angular velocity in radians per second

b2Rot_GetAngle

Calculates the angle of a rotation by computing the arctangent of the sine component divided by the cosine component using Math.atan2.

b2Rot_GetAngle(q: b2Rot): number
Parameters
q (b2Rot) A rotation object containing cosine (c) and sine (s) components.
Returns
number: The angle in radians, calculated using arctangent of s/c.

b2Rot_GetXAxis

Extracts the x-axis direction vector from a rotation matrix by returning a vector containing the cosine component in x and sine component in y.

b2Rot_GetXAxis(q: b2Rot): b2Vec2
Parameters
q (b2Rot) A rotation matrix containing cosine (c) and sine (s) components
Returns
b2Vec2: A 2D vector representing the x-axis direction (c, s)

b2Rot_GetYAxis

Extracts the Y axis vector from a rotation matrix by returning the vector (-sin, cos). This represents the vertical basis vector of the rotated coordinate system.

b2Rot_GetYAxis(q: b2Rot): b2Vec2
Parameters
q (b2Rot) A rotation matrix containing cosine (c) and sine (s) components
Returns
b2Vec2: A 2D vector (-sin, cos) representing the Y axis of the rotation

b2MulRot

Performs rotation multiplication by combining the cosine and sine components of two b2Rot objects using the formula: result.c = q4.c * r.c - q4.s * r.s result.s = q4.s * r.c + q4.c * r.s

b2MulRot(q: b2Rot, r: b2Rot): b2Rot
Parameters
q (b2Rot) First rotation
r (b2Rot) Second rotation
Returns
b2Rot: A new rotation representing the product of the two input rotations

b2InvMulRot

Computes the product of the inverse of rotation q with rotation r. For rotations, the inverse multiplication is equivalent to using the transpose of the rotation matrix.

b2InvMulRot(q: b2Rot, r: b2Rot): b2Rot
Parameters
q (b2Rot) The first rotation to be inverted
r (b2Rot) The second rotation to be multiplied
Returns
b2Rot: A new rotation representing q^-1 * r

b2RelativeAngle

Computes the angle between two rotations by using their sine and cosine components. The result is the angle needed to rotate from rotation 'a' to rotation 'b'.

b2RelativeAngle(b: b2Rot, a: b2Rot): number
Parameters
b (b2Rot) The first rotation
a (b2Rot) The second rotation
Returns
number: The relative angle in radians between the two rotations

b2UnwindAngle

This function takes an angle in radians and ensures it falls within the range [-π, π] by adding or subtracting 2π as needed. If the input angle is already within the valid range, it is returned unchanged.

b2UnwindAngle(angle: number): number
Parameters
angle (number) The input angle in radians to normalize.
Returns
number: The normalized angle in radians within the range [-π, π].

b2RotateVector

Applies a 2D rotation to a vector using the formula: x' = cx - sy y' = sx + cy where (x,y) is the input vector and (c,s) represents the rotation

b2RotateVector(q: b2Rot, v: b2Vec2): b2Vec2
Parameters
q (b2Rot) A rotation object containing cosine (c) and sine (s) components
v (b2Vec2) The vector to rotate
Returns
b2Vec2: A new vector representing the rotated result

b2InvRotateVector

Applies the inverse of the rotation defined by q4 to vector v. The operation is equivalent to multiplying the vector by the transpose of the rotation matrix represented by q4.

b2InvRotateVector(q: b2Rot, v: b2Vec2): b2Vec2
Parameters
q (b2Rot) A rotation matrix containing cosine (c) and sine (s) components
v (b2Vec2) The vector to be inversely rotated
Returns
b2Vec2: A new vector representing the inverse rotation of v by q4

b2TransformPoint

Applies a rigid body transformation to a 2D point. The transformation consists of a rotation followed by a translation. The rotation is applied using the rotation matrix stored in t.q (cosine and sine components), and the translation is applied using the position vector stored in t.p.

b2TransformPoint(t: b2Transform, p: b2Vec2): b2Vec2
Parameters
t (b2Transform) A transform containing position (p) and rotation (q) components
p (b2Vec2) The point to transform
Returns
b2Vec2: The transformed point

b2InvTransformPoint

Computes the inverse transform of a point by first translating relative to the transform's position, then applying the inverse rotation. The rotation inverse is computed using the transpose of the rotation matrix.

b2InvTransformPoint(t: b2Transform, p: b2Vec2): b2Vec2
Parameters
t (b2Transform) A transform containing position (p) and rotation (q) components
p (b2Vec2) The point to transform
Returns
b2Vec2: The inverse transformed point

b2MulTransforms

Combines two transforms by first multiplying their rotations (q components), then rotating B's position vector by A's rotation and adding it to A's position. The result represents the combined transformation of first applying B, then A.

b2MulTransforms(A: b2Transform, B: b2Transform): b2Transform
Parameters
A (b2Transform) The first transform
B (b2Transform) The second transform
Returns
b2Transform: A new transform C that represents the multiplication of A and B

b2InvMulTransforms

Calculates A^-1 * B, where A^-1 is the inverse of transform A. The result combines both the rotational and translational components of the transforms using their quaternion and position vectors.

b2InvMulTransforms(A: b2Transform, B: b2Transform): b2Transform
Parameters
A (b2Transform) The first transform
B (b2Transform) The second transform
Returns
b2Transform: A new transform representing the inverse multiplication of A and B

b2MulMV

Performs matrix-vector multiplication of the form Av, where A is a 2x2 matrix and v is a 2D vector. The result is a new 2D vector.

b2MulMV(A: b2Mat22, v: b2Vec2): b2Vec2
Parameters
A (b2Mat22) A 2x2 matrix with components cx and cy, each containing x and y values
v (b2Vec2) A 2D vector with x and y components
Returns
b2Vec2: The resulting 2D vector from the matrix-vector multiplication

b2GetInverse22

Computes the inverse of a 2x2 matrix using the formula: For matrix [[a,b],[c,d]], inverse = (1/det) * [[d,-c],[-b,a]] where det = ad-bc

b2GetInverse22(A: b2Mat22): b2Mat22
Parameters
A (b2Mat22) The input 2x2 matrix to invert
Returns
b2Mat22: The inverse of matrix A. If the determinant is 0, returns a matrix with undefined values

b2Solve22

Solves the system using the formula: x = (1/det) * [a22 -a12] * [b.x] [-a21 a11] [b.y] where det = a11a22 - a12a21

b2Solve22(A: b2Mat22, b: b2Vec2): b2Vec2
Parameters
A (b2Mat22) A 2x2 matrix represented as two column vectors (cx, cy)
b (b2Vec2) A 2D vector representing the right-hand side of the equation
Returns
b2Vec2: The solution vector x that satisfies Ax = b. Returns a zero vector if the system is singular (det = 0)

b2AABB_Contains

Tests if AABB 'b' is completely contained within AABB 'a' by comparing their bounds. An AABB contains another if its lower bounds are less than or equal to the other's lower bounds and its upper bounds are greater than or equal to the other's upper bounds.

b2AABB_Contains(a: b2AABB, b: b2AABB): boolean
Parameters
a (b2AABB) The containing AABB
b (b2AABB) The AABB to test for containment
Returns
boolean: True if AABB 'a' completely contains AABB 'b', false otherwise

b2AABB_Center

Computes the center point of an AABB by averaging its lower and upper bounds in both X and Y dimensions.

b2AABB_Center(a: b2AABB): b2Vec2
Parameters
a (b2AABB) The AABB object containing lowerBound and upperBound coordinates.
Returns
b2Vec2: A 2D vector representing the center point of the AABB.

b2AABB_Extents

Computes the extents of an AABB by calculating half the difference between its upper and lower bounds in both x and y dimensions.

b2AABB_Extents(a: b2AABB): b2Vec2
Parameters
a (b2AABB) The AABB to calculate extents for
Returns
b2Vec2: A vector containing the half-width and half-height of the AABB

b2AABB_Union

Computes the union of two axis-aligned bounding boxes by creating a new AABB with a lower bound at the minimum coordinates and an upper bound at the maximum coordinates of both input boxes.

b2AABB_Union(a: b2AABB, b: b2AABB): b2AABB
Parameters
a (b2AABB) The first axis-aligned bounding box
b (b2AABB) The second axis-aligned bounding box
Returns
b2AABB: A new AABB that encompasses both input boxes

b2IsValid

This function performs a validation check on a number by ensuring it is both finite and not NaN (Not a Number).

b2IsValid(a: number): boolean
Parameters
a (number) The number to validate.
Returns
boolean: True if the number is valid (finite and not NaN), false otherwise.

b2IsValid

This function performs a validation check on a number by ensuring it is both finite and not NaN (Not a Number).

b2IsValid(a: number): boolean
Parameters
a (number) The number to validate.
Returns
boolean: True if the number is valid (finite and not NaN), false otherwise.

b2Vec2_IsValid

Validates a b2Vec2 object by checking if it exists and its components are valid numbers.

b2Vec2_IsValid(v: b2Vec2): boolean
Parameters
v (b2Vec2) The vector to validate, containing x and y components.
Returns
boolean: True if the vector exists and both x and y components are valid numbers.

b2Vec2_IsValid

Validates a b2Vec2 object by checking if it exists and its components are valid numbers.

b2Vec2_IsValid(v: b2Vec2): boolean
Parameters
v (b2Vec2) The vector to validate, containing x and y components.
Returns
boolean: True if the vector exists and both x and y components are valid numbers.

b2Rot_IsValid

Checks if a b2Rot object is valid by verifying:

  1. The object exists
  2. Both sine and cosine components contain valid numbers
  3. The rotation is properly normalized (s² + c² = 1)
b2Rot_IsValid(q: b2Rot): boolean
Parameters
q (b2Rot) A rotation object containing sine (s) and cosine (c) components
Returns
boolean: True if the rotation is valid, false otherwise

b2Rot_IsValid

Checks if a b2Rot object is valid by verifying:

  1. The object exists
  2. Both sine and cosine components contain valid numbers
  3. The rotation is properly normalized (s² + c² = 1)
b2Rot_IsValid(q4: b2Rot): boolean
Parameters
q4 (b2Rot) A rotation object containing sine (s) and cosine (c) components
Returns
boolean: True if the rotation is valid, false otherwise

b2AABB_IsValid

Checks if an AABB is valid by verifying:

  1. The AABB object exists
  2. The width (upperBoundX - lowerBoundX) is non-negative
  3. The height (upperBoundY - lowerBoundY) is non-negative
  4. All coordinate values are valid numbers
b2AABB_IsValid(aabb: b2AABB): boolean
Parameters
aabb (b2AABB) The AABB to validate
Returns
boolean: True if the AABB exists and has valid dimensions and coordinates

b2AABB_IsValid

Checks if an AABB is valid by verifying:

  1. The AABB object exists
  2. The width (upperBoundX - lowerBoundX) is non-negative
  3. The height (upperBoundY - lowerBoundY) is non-negative
  4. All coordinate values are valid numbers
b2AABB_IsValid(aabb: b2AABB): boolean
Parameters
aabb (b2AABB) The AABB to validate
Returns
boolean: True if the AABB exists and has valid dimensions and coordinates

b2Normalize

Normalizes the input vector by dividing its components by its length. If the vector's length is greater than the epsilon value, the function returns a new vector with the same direction but unit length.

b2Normalize(v: b2Vec2): b2Vec2
Parameters
v (b2Vec2) The vector to normalize.
Returns
b2Vec2: Returns a new normalized b2Vec2 if successful. If the vector length is less than epsilon, returns a zero vector (0,0).

b2Normalize

Normalizes the input vector by dividing its components by its length. If the vector's length is greater than the epsilon value, the function returns a new vector with the same direction but unit length.

b2Normalize(v: b2Vec2): (b2Vec2 | boolean)
Parameters
v (b2Vec2) The vector to normalize.
Returns
(b2Vec2 | boolean): Returns a new normalized b2Vec2 if successful, or false if the input is null. If the vector length is less than epsilon, returns a zero vector (0,0).

b2NormalizeChecked

Normalizes a 2D vector and performs length validation.

b2NormalizeChecked(v: b2Vec2): b2Vec2
Parameters
v (b2Vec2) The vector to normalize.
Returns
b2Vec2: A new normalized vector with unit length.
Throws
  • Error: Throws an assertion error if the vector length is less than or equal to eps.

b2NormalizeChecked

Normalizes a 2D vector and performs length validation.

b2NormalizeChecked(v: b2Vec2): b2Vec2
Parameters
v (b2Vec2) The vector to normalize.
Returns
b2Vec2: A new normalized vector with unit length.
Throws
  • Error: Throws an assertion error if the vector length is less than or equal to eps.

MotorJoint

MotorJoint

MotorJoint

b2MotorJoint_SetLinearOffset

Updates the target linear offset of a motor joint. The linear offset represents the desired translation between the two bodies connected by the joint.

b2MotorJoint_SetLinearOffset(jointId: b2JointId, linearOffset: b2Vec2): void
Parameters
jointId (b2JointId) The identifier for the motor joint to modify.
linearOffset (b2Vec2) The desired linear offset in local coordinates.
Returns
void:
Throws
  • Error: Throws if the joint is not a motor joint or if the jointId is invalid.

b2MotorJoint_GetLinearOffset

Gets the linear offset of a motor joint.

b2MotorJoint_GetLinearOffset(jointId: b2JointId): b2Vec2
Parameters
jointId (b2JointId) The identifier of the motor joint.
Returns
b2Vec2: The linear offset vector of the motor joint.
Throws
  • Error: If the joint is not a motor joint or the joint ID is invalid.

b2MotorJoint_SetAngularOffset

Sets the target angular offset for a motor joint, which defines the desired relative rotation between the connected bodies. The input angle is automatically clamped to the range [-π, π].

b2MotorJoint_SetAngularOffset(jointId: b2JointId, angularOffset: number): void
Parameters
jointId (b2JointId) The identifier for the motor joint to modify.
angularOffset (number) The desired angular offset in radians, clamped between -π and π.
Returns
void:
Throws
  • Error: Throws if the joint is not a motor joint type.

b2MotorJoint_GetAngularOffset

b2MotorJoint_GetAngularOffset(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier of the motor joint.
Returns
number: The angular offset value of the motor joint in radians.
Throws
  • Error: Throws if the joint is not a motor joint or if the joint ID is invalid.

b2MotorJoint_SetMaxForce

Sets the maximum force that can be applied by a motor joint.

b2MotorJoint_SetMaxForce(jointId: b2JointId, maxForce: number): void
Parameters
jointId (b2JointId) The identifier for the motor joint
maxForce (number) The maximum force value to set. Will be clamped to non-negative values.
Returns
void:
Throws
  • Error: If the joint is not a motor joint type

b2MotorJoint_GetMaxForce

Gets the maximum force value from a motor joint.

b2MotorJoint_GetMaxForce(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the motor joint.
Returns
number: The maximum force value of the motor joint.
Throws
  • Error: If the joint is not of type b2_motorJoint.

b2MotorJoint_SetMaxTorque

Sets the maximum torque that can be applied by a motor joint.

b2MotorJoint_SetMaxTorque(jointId: b2JointId, maxTorque: number): void
Parameters
jointId (b2JointId) The identifier for the motor joint.
maxTorque (number) The maximum torque value. Will be clamped to non-negative values.
Returns
void:
Throws
  • Error: If the joint is not of type b2_motorJoint.

b2MotorJoint_GetMaxTorque

Gets the maximum torque value for a motor joint.

b2MotorJoint_GetMaxTorque(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the motor joint.
Returns
number: The maximum torque value of the motor joint.
Throws
  • Error: If the joint is not of type b2_motorJoint.

b2MotorJoint_SetCorrectionFactor

Sets the position correction factor for a motor joint, which determines how much position error is corrected each time step. The correction factor is automatically clamped between 0 and 1.

b2MotorJoint_SetCorrectionFactor(jointId: b2JointId, correctionFactor: number): void
Parameters
jointId (b2JointId) The identifier for the motor joint.
correctionFactor (number) The correction factor value, clamped between 0 and 1.
Returns
void:
Throws
  • Error: Throws an error if the joint is not a motor joint type.

b2MotorJoint_GetCorrectionFactor

Gets the correction factor of a motor joint.

b2MotorJoint_GetCorrectionFactor(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the motor joint.
Returns
number: The correction factor value of the motor joint.
Throws
  • Error: If the joint is not a motor joint type.

MouseJoint

MouseJoint

MouseJoint

b2MouseJoint_SetTarget

Updates the target position of a mouse joint by cloning the provided target vector. The joint must be of type b2_mouseJoint.

b2MouseJoint_SetTarget(jointId: b2JointId, target: b2Vec2): void
Parameters
jointId (b2JointId) The identifier of the mouse joint to modify.
target (b2Vec2) The new target position vector to set.
Returns
void:
Throws
  • Error: Throws an error if the joint is not of type b2_mouseJoint.

b2MouseJoint_GetTarget

b2MouseJoint_GetTarget(jointId: b2JointId): b2Vec2
Parameters
jointId (b2JointId) The identifier of the mouse joint.
Returns
b2Vec2: The target point of the mouse joint.
Throws
  • Error: If the joint is not of type b2_mouseJoint.

b2MouseJoint_SetSpringHertz

b2MouseJoint_SetSpringHertz(jointId: b2JointId, hertz: number): void
Parameters
jointId (b2JointId) The identifier for the mouse joint to modify.
hertz (number) The spring frequency in Hertz (Hz).
Returns
void:
Throws
  • Error: Throws if the joint is not a mouse joint type.

b2MouseJoint_GetSpringHertz

Gets the spring frequency in Hertz from a mouse joint.

b2MouseJoint_GetSpringHertz(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the mouse joint.
Returns
number: The spring frequency in Hertz.
Throws
  • Error: If the joint is not a mouse joint type.

b2MouseJoint_SetSpringDampingRatio

Sets the damping ratio for a mouse joint.

b2MouseJoint_SetSpringDampingRatio(jointId: b2JointId, dampingRatio: number): void
Parameters
jointId (b2JointId) The identifier for the mouse joint to modify.
dampingRatio (number) The damping ratio value to set.
Returns
void:
Throws
  • Error: Throws if the joint is not a mouse joint type.

b2MouseJoint_GetSpringDampingRatio

Gets the spring damping ratio of a mouse joint.

b2MouseJoint_GetSpringDampingRatio(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier of the mouse joint.
Returns
number: The spring damping ratio value of the mouse joint.
Throws
  • Error: Throws if the joint is not a mouse joint type.

b2MouseJoint_SetMaxForce

Sets the maximum force that can be applied by the mouse joint to maintain its constraint.

b2MouseJoint_SetMaxForce(jointId: b2JointId, maxForce: number): void
Parameters
jointId (b2JointId) The identifier for the mouse joint to modify.
maxForce (number) The maximum force value to set for the joint.
Returns
void:
Throws
  • Error: Throws an error if the joint is not of type b2_mouseJoint.

b2MouseJoint_GetMaxForce

Gets the maximum force value from a mouse joint.

b2MouseJoint_GetMaxForce(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the mouse joint.
Returns
number: The maximum force value of the mouse joint.
Throws
  • Error: If the joint is not of type b2_mouseJoint.

PrismaticJoint

PrismaticJoint

PrismaticJoint

b2PrismaticJoint_EnableSpring

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2PrismaticJoint_EnableSpring

b2PrismaticJoint_EnableSpring

Sets the spring state of a prismatic joint. When the spring state changes, the spring impulse is reset to zero. If the state doesn't change, no action is taken.

b2PrismaticJoint_EnableSpring(jointId: b2JointId, enableSpring: boolean): void
Parameters
jointId (b2JointId) The identifier of the prismatic joint to modify.
enableSpring (boolean) Whether to enable (true) or disable (false) the spring.
Returns
void:
Throws
  • Error: Throws if the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_IsSpringEnabled

b2PrismaticJoint_IsSpringEnabled(jointId: b2JointId): boolean
Parameters
jointId (b2JointId) The identifier for the prismatic joint to check.
Returns
boolean: True if the spring mechanism is enabled, false otherwise.
Throws
  • Error: Throws an error if the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_SetSpringHertz

Updates the spring frequency of a prismatic joint. The joint must be of type b2_prismaticJoint.

b2PrismaticJoint_SetSpringHertz(jointId: b2JointId, hertz: number): void
Parameters
jointId (b2JointId) The identifier for the prismatic joint to modify.
hertz (number) The spring frequency in Hertz.
Returns
void:
Throws
  • Error: Throws an error if the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_GetSpringHertz

Gets the spring frequency in Hertz for a prismatic joint.

b2PrismaticJoint_GetSpringHertz(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the prismatic joint.
Returns
number: The spring frequency in Hertz.
Throws
  • Error: If the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_SetSpringDampingRatio

Sets the spring damping ratio for a prismatic joint. The joint must be of type b2_prismaticJoint.

b2PrismaticJoint_SetSpringDampingRatio(jointId: b2JointId, dampingRatio: number): void
Parameters
jointId (b2JointId) The identifier for the prismatic joint.
dampingRatio (number) The damping ratio for the spring.
Returns
void:
Throws
  • Error: Throws an error if the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_GetSpringDampingRatio

Gets the spring damping ratio of a prismatic joint.

b2PrismaticJoint_GetSpringDampingRatio(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the prismatic joint.
Returns
number: The spring damping ratio value.
Throws
  • Error: Throws an error if the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_EnableLimit

Enables or disables the translation limits on a prismatic joint. When the limit is disabled, the joint's limit impulses are reset to zero.

b2PrismaticJoint_EnableLimit(jointId: b2JointId, enableLimit: boolean): void
Parameters
jointId (b2JointId) The identifier for the prismatic joint
enableLimit (boolean) True to enable the translation limit, false to disable it
Returns
void:
Throws
  • Error: If the joint identified by jointId is not a prismatic joint

b2PrismaticJoint_IsLimitEnabled

b2PrismaticJoint_IsLimitEnabled(jointId: b2JointId): boolean
Parameters
jointId (b2JointId) The identifier for the prismatic joint to check.
Returns
boolean: True if the limit is enabled for the joint, false otherwise.
Throws
  • Error: Throws an error if the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_GetLowerLimit

b2PrismaticJoint_GetLowerLimit(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the prismatic joint.
Returns
number: The lower translation limit of the prismatic joint.
Throws
  • Error: Throws an error if the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_GetUpperLimit

b2PrismaticJoint_GetUpperLimit(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the prismatic joint.
Returns
number: The upper translation limit of the prismatic joint.
Throws
  • Error: If the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_SetLimits

Sets new translation limits for a prismatic joint. The function automatically orders the limits so that the lower value is always less than or equal to the upper value. When the limits change, the joint's impulses are reset to zero.

b2PrismaticJoint_SetLimits(jointId: b2JointId, lower: number, upper: number): void
Parameters
jointId (b2JointId) The identifier for the prismatic joint.
lower (number) The lower translation limit.
upper (number) The upper translation limit.
Returns
void:
Throws
  • Error: If the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_EnableMotor

Enables or disables the motor on a prismatic joint. When the motor is disabled, the motor impulse is reset to zero.

b2PrismaticJoint_EnableMotor(jointId: b2JointId, enableMotor: boolean): void
Parameters
jointId (b2JointId) The identifier for the prismatic joint
enableMotor (boolean) True to enable the motor, false to disable it
Returns
void:
Throws
  • Error: If the joint is not of type b2_prismaticJoint

b2PrismaticJoint_IsMotorEnabled

b2PrismaticJoint_IsMotorEnabled(jointId: b2JointId): boolean
Parameters
jointId (b2JointId) The identifier for the prismatic joint to check.
Returns
boolean: True if the motor is enabled, false otherwise.
Throws
  • Error: Throws if the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_SetMotorSpeed

b2PrismaticJoint_SetMotorSpeed(jointId: b2JointId, motorSpeed: number): void
Parameters
jointId (b2JointId) The identifier for the prismatic joint to modify.
motorSpeed (number) The desired motor speed in radians per second.
Returns
void:
Throws
  • Error: Throws if the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_GetMotorSpeed

Gets the motor speed of a prismatic joint.

b2PrismaticJoint_GetMotorSpeed(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the prismatic joint.
Returns
number: The current motor speed of the prismatic joint.
Throws
  • Error: If the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_GetMotorForce

Gets the current motor force of a prismatic joint. The force is calculated by multiplying the joint's motor impulse by the inverse of the world's time step.

b2PrismaticJoint_GetMotorForce(jointId: b2JointId): number
Parameters
jointId (b2JointId) The ID of the prismatic joint
Returns
number: The current motor force in Newtons
Throws
  • Error: Throws if the joint type is not a prismatic joint

b2PrismaticJoint_SetMaxMotorForce

Sets the maximum motor force for a prismatic joint.

b2PrismaticJoint_SetMaxMotorForce(jointId: b2JointId, force: number): void
Parameters
jointId (b2JointId) The identifier for the prismatic joint.
force (number) The maximum force the motor can apply.
Returns
void:
Throws
  • Error: Throws if the joint is not of type b2_prismaticJoint.

b2PrismaticJoint_GetMaxMotorForce

Gets the maximum motor force of a prismatic joint.

b2PrismaticJoint_GetMaxMotorForce(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the prismatic joint.
Returns
number: The maximum force that can be applied by the joint's motor.
Throws
  • Error: If the joint is not of type b2_prismaticJoint.

RevoluteJoint

RevoluteJoint

RevoluteJoint

b2RevoluteJoint_EnableSpring

Enables or disables the spring functionality of a revolute joint. When the spring state changes, the spring impulse is reset to zero.

b2RevoluteJoint_EnableSpring(jointId: b2JointId, enableSpring: boolean): void
Parameters
jointId (b2JointId) The identifier of the revolute joint to modify
enableSpring (boolean) True to enable the spring, false to disable it
Returns
void:
Throws
  • Error: If the joint is not of type b2_revoluteJoint

b2RevoluteJoint_IsSpringEnabled

b2RevoluteJoint_IsSpringEnabled(jointId: b2JointId): boolean
Parameters
jointId (b2JointId) The identifier for the revolute joint to check.
Returns
boolean: True if spring functionality is enabled, false otherwise.
Throws
  • Error: Throws if the joint is not of type b2_revoluteJoint.

b2RevoluteJoint_SetSpringHertz

Sets the spring oscillation frequency for a revolute joint. The joint must be of type b2_revoluteJoint.

b2RevoluteJoint_SetSpringHertz(jointId: b2JointId, hertz: number): void
Parameters
jointId (b2JointId) The identifier for the revolute joint to modify.
hertz (number) The spring frequency in Hertz (Hz).
Returns
void:
Throws
  • Error: Throws an error if the joint is not of type b2_revoluteJoint.

b2RevoluteJoint_GetSpringHertz

Gets the spring frequency in Hertz for a revolute joint.

b2RevoluteJoint_GetSpringHertz(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the revolute joint.
Returns
number: The spring frequency in Hertz.
Throws
  • Error: If the joint is not of type b2_revoluteJoint.

b2RevoluteJoint_SetSpringDampingRatio

Sets the damping ratio for a revolute joint's spring.

b2RevoluteJoint_SetSpringDampingRatio(jointId: b2JointId, dampingRatio: number): void
Parameters
jointId (b2JointId) The identifier for the revolute joint.
dampingRatio (number) The damping ratio for the spring.
Returns
void:
Throws
  • Error: Throws if the joint is not of type b2_revoluteJoint.

b2RevoluteJoint_GetSpringDampingRatio

Gets the spring damping ratio of a revolute joint.

b2RevoluteJoint_GetSpringDampingRatio(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier of the revolute joint.
Returns
number: The spring damping ratio value of the revolute joint.
Throws
  • Error: If the joint is not of type b2_revoluteJoint.

b2RevoluteJoint_GetAngle

Calculates the relative angle between two bodies connected by a revolute joint by comparing their transforms and subtracting the joint's reference angle. The result is unwound to ensure consistent angle representation.

b2RevoluteJoint_GetAngle(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the revolute joint.
Returns
number: The current angle in radians between the two connected bodies, relative to the reference angle.

b2RevoluteJoint_EnableLimit

When enabled, the joint will restrict rotation to be between its upper and lower angle limits. When the limit state changes, the joint's limit impulses are reset to zero.

b2RevoluteJoint_EnableLimit(jointId: b2JointId, enableLimit: boolean): void
Parameters
jointId (b2JointId) The identifier for the revolute joint.
enableLimit (boolean) True to enable the joint limits, false to disable them.
Returns
void:
Throws
  • Error: Throws if the joint is not of type b2_revoluteJoint.

b2RevoluteJoint_IsLimitEnabled

b2RevoluteJoint_IsLimitEnabled(jointId: b2JointId): boolean
Parameters
jointId (b2JointId) The identifier for the revolute joint to check.
Returns
boolean: True if the joint's limit is enabled, false otherwise.
Throws
  • Error: Throws if the joint is not of type b2_revoluteJoint.

b2RevoluteJoint_GetLowerLimit

Gets the lower angle limit of a revolute joint.

b2RevoluteJoint_GetLowerLimit(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the revolute joint.
Returns
number: The lower angle limit in radians.
Throws
  • Error: If the joint is not of type b2_revoluteJoint.

b2RevoluteJoint_GetUpperLimit

Gets the upper angle limit of a revolute joint.

b2RevoluteJoint_GetUpperLimit(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the revolute joint.
Returns
number: The upper angle limit in radians.
Throws
  • Error: If the joint is not of type b2_revoluteJoint.

b2RevoluteJoint_SetLimits

Sets the lower and upper angle limits for a revolute joint. The function automatically orders the limits so that the lower value is always less than or equal to the upper value. When the limits change, the joint impulses are reset to zero.

b2RevoluteJoint_SetLimits(jointId: b2JointId, lower: number, upper: number): void
Parameters
jointId (b2JointId) The identifier for the revolute joint to modify
lower (number) The lower angle limit in radians
upper (number) The upper angle limit in radians
Returns
void:
Throws
  • Error: If the joint is not of type b2_revoluteJoint

b2RevoluteJoint_EnableMotor

Enables or disables the motor on a revolute joint. When the motor is disabled, its accumulated impulse is reset to zero.

b2RevoluteJoint_EnableMotor(jointId: b2JointId, enableMotor: boolean): void
Parameters
jointId (b2JointId) The identifier for the revolute joint
enableMotor (boolean) True to enable the joint's motor, false to disable it
Returns
void:
Throws
  • Error: If the joint is not of type b2_revoluteJoint

b2RevoluteJoint_IsMotorEnabled

b2RevoluteJoint_IsMotorEnabled(jointId: b2JointId): boolean
Parameters
jointId (b2JointId) The identifier for the revolute joint to check.
Returns
boolean: True if the motor is enabled, false otherwise.
Throws
  • Error: Throws if the joint is not of type b2_revoluteJoint.

b2RevoluteJoint_SetMotorSpeed

Sets the angular velocity for the motor of a revolute joint. A positive velocity means the joint will rotate counterclockwise.

b2RevoluteJoint_SetMotorSpeed(jointId: b2JointId, motorSpeed: number): void
Parameters
jointId (b2JointId) The identifier for the revolute joint.
motorSpeed (number) The desired motor speed in radians per second.
Returns
void:
Throws
  • Error: Throws an error if the joint is not of type b2_revoluteJoint.

b2RevoluteJoint_GetMotorSpeed

Gets the motor speed of a revolute joint.

b2RevoluteJoint_GetMotorSpeed(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier of the revolute joint.
Returns
number: The current motor speed in radians per second.
Throws
  • Error: If the joint is not of type b2_revoluteJoint.

b2RevoluteJoint_GetMotorTorque

Calculates the motor torque by multiplying the motor impulse by the inverse of the time step. The joint must be of type b2_revoluteJoint.

b2RevoluteJoint_GetMotorTorque(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the revolute joint.
Returns
number: The current motor torque in Newton-meters.
Throws
  • Error: If the joint type is not b2_revoluteJoint.

b2RevoluteJoint_SetMaxMotorTorque

Sets the maximum motor torque for a revolute joint.

b2RevoluteJoint_SetMaxMotorTorque(jointId: b2JointId, torque: number): void
Parameters
jointId (b2JointId) The identifier for the revolute joint.
torque (number) The maximum motor torque value to set.
Returns
void:
Throws
  • Error: Throws if the joint is not of type b2_revoluteJoint.

b2RevoluteJoint_GetMaxMotorTorque

Gets the maximum motor torque of a revolute joint.

b2RevoluteJoint_GetMaxMotorTorque(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the revolute joint.
Returns
number: The maximum motor torque value.
Throws
  • Error: If the joint is not of type b2_revoluteJoint.

Shape

Shape

Shape

b2CreateCircleShape

Creates a circle shape and attaches it to a body.

b2CreateCircleShape(bodyId: b2BodyId, def: b2ShapeDef, circle: b2Circle): b2ShapeId
Parameters
bodyId (b2BodyId) The identifier of the body to attach the shape to
def (b2ShapeDef) The shape definition containing properties like friction and density
circle (b2Circle) The circle geometry definition
Returns
b2ShapeId: The identifier of the created circle shape

b2CreateCapsuleShape

Creates a capsule shape if the distance between centers is greater than b2_linearSlop. If centers are closer than b2_linearSlop, creates a circle shape instead with radius equal to the capsule radius and center at the midpoint between capsule centers.

b2CreateCapsuleShape(bodyId: b2BodyId, def: b2ShapeDef, capsule: b2Capsule): b2ShapeId
Parameters
bodyId (b2BodyId) The body ID to attach the shape to
def (b2ShapeDef) The shape definition parameters
capsule (b2Capsule) The capsule geometry containing center1, center2 and radius
Returns
b2ShapeId: The ID of the created shape

b2CreatePolygonShape

Creates a polygon shape and attaches it to a body.

b2CreatePolygonShape(bodyId: b2BodyId, def: b2ShapeDef, polygon: b2Polygon): b2ShapeId
Parameters
bodyId (b2BodyId) The identifier of the body to attach the shape to
def (b2ShapeDef) The shape definition containing common shape properties
polygon (b2Polygon) The polygon data including vertices and radius
Returns
b2ShapeId: The identifier of the created polygon shape
Throws
  • Error: Throws an assertion error if the polygon radius is invalid or negative

b2CreateSegmentShape

Creates a segment shape between two points and attaches it to the specified body. The function validates that the segment length is greater than b2_linearSlop before creating the shape.

b2CreateSegmentShape(bodyId: b2BodyId, def: b2ShapeDef, segment: b2Segment): b2ShapeId
Parameters
bodyId (b2BodyId) The ID of the body to attach the shape to
def (b2ShapeDef) The shape definition parameters
segment (b2Segment) The segment geometry defined by point1 and point2
Returns
b2ShapeId: The ID of the created segment shape
Throws
  • Error: Throws an assertion error if the segment length squared is less than or equal to b2_linearSlop squared

b2DestroyShape

Removes a shape from the physics world. If the parent body has automatic mass calculation enabled, the body's mass properties are recalculated after the shape is destroyed. The function performs the following operations:

  1. Retrieves the world and shape from the provided shapeId
  2. Destroys the shape internally
  3. Updates the parent body's mass data if automatic mass calculation is enabled
b2DestroyShape(shapeId: b2ShapeId)
Parameters
shapeId (b2ShapeId) The identifier of the shape to destroy.

b2CreateChain

Creates a chain shape composed of connected line segments attached to a body. The chain can be either a closed loop or an open chain.

b2CreateChain(bodyId: b2BodyId, def: b2ChainDef): b2ChainId
Parameters
bodyId (b2BodyId) The ID of the body to attach the chain to
def (b2ChainDef) The chain definition containing:
  • {number} count - Number of vertices (must be >= 4)
  • {b2Vec2[]} points - Array of vertex points
  • {boolean} isLoop - Whether the chain forms a closed loop
  • {number} friction - Friction coefficient (must be >= 0)
  • {number} restitution - Restitution coefficient (must be >= 0)
  • {b2Filter} filter - Collision filter data
  • {*} userData - User data pointer
Returns
b2ChainId: The ID of the created chain shape
Throws
  • Error: Throws assertion error if friction or restitution are invalid/negative, or if count is less than 4

b2DestroyChain

Destroys a chain of shapes attached to a body in a Box2D world. The function removes all shapes associated with the chain and frees the chain ID from the world's chain ID pool.

b2DestroyChain(chainId: b2ChainId): void
Parameters
chainId (b2ChainId) The identifier for the chain to be destroyed, containing world and index information
Returns
void:
Throws
  • Error: Throws an assertion error if the chain is not found in the body's chain list

b2Shape_GetBody

Retrieves the body ID for a given shape by first accessing the world object, then getting the shape from the world, and finally creating a body ID from the shape's stored body reference.

b2Shape_GetBody(shapeId: b2ShapeId): b2BodyId
Parameters
shapeId (b2ShapeId) The ID of the shape to query.
Returns
b2BodyId: The ID of the body that owns the shape.

b2Shape_SetUserData

Associates arbitrary user data with a shape identified by shapeId. The shape must exist in the world referenced by the shapeId. The function retrieves the shape from the world and updates its userData property.

b2Shape_SetUserData(shapeId: b2ShapeId, userData: any): void
Parameters
shapeId (b2ShapeId) The identifier of the shape to modify.
userData (any) The user data to associate with the shape.
Returns
void:

b2Shape_GetUserData

This function retrieves the user data that was previously attached to a shape by looking up the shape in the world using the provided shape ID.

b2Shape_GetUserData(shapeId: b2ShapeId): void
Parameters
shapeId (b2ShapeId) The identifier for the shape.
Returns
void: The user data associated with the shape.

b2Shape_IsSensor

Retrieves a shape from the physics world using its ID and returns whether it is configured as a sensor. Sensor shapes detect collisions but do not generate physical responses.

b2Shape_IsSensor(shapeId: b2ShapeId): boolean
Parameters
shapeId (b2ShapeId) The identifier for the shape to check.
Returns
boolean: True if the shape is a sensor, false otherwise.

b2Shape_TestPoint

Transforms the test point into the shape's local space and performs point-in-shape testing based on the shape type (capsule, circle, or polygon). Returns false for unrecognized shape types.

b2Shape_TestPoint(shapeId: b2ShapeId, point: b2Vec2): boolean
Parameters
shapeId (b2ShapeId) The identifier for the shape to test against
point (b2Vec2) The world space point to test
Returns
boolean: True if the point is inside the shape, false otherwise

b2Shape_RayCast

Performs a ray cast against a shape in world space, transforming the input/output between local and world coordinates.

b2Shape_RayCast(shapeId: b2ShapeId, origin: b2Vec2, translation: b2Vec2): b2CastOutput
Parameters
shapeId (b2ShapeId) The identifier for the shape to test
origin (b2Vec2) The starting point of the ray in world coordinates
translation (b2Vec2) The direction and length of the ray in world coordinates
Returns
b2CastOutput: The ray cast results containing:
  • hit: boolean indicating if the ray intersects the shape
  • point: intersection point in world coordinates (if hit is true)
  • normal: surface normal at intersection in world coordinates (if hit is true)
  • fraction: fraction of translation where intersection occurs (if hit is true)
Throws
  • Error: Throws assertion error if shape type is invalid

b2Shape_SetDensity

Sets a new density value for the specified shape. If the new density matches the current density, no changes are made. The function performs validation to ensure the density is a valid non-negative number.

b2Shape_SetDensity(shapeId: b2ShapeId, density: number): void
Parameters
shapeId (b2ShapeId) The identifier of the shape to modify.
density (number) The new density value. Must be non-negative.
Returns
void:
Throws
  • Error: Throws an assertion error if the density is invalid or negative.

b2Shape_GetDensity

Retrieves the density property of a shape by first accessing the world object using the world identifier stored in the shapeId, then accessing the specific shape within that world.

b2Shape_GetDensity(shapeId: b2ShapeId): number
Parameters
shapeId (b2ShapeId) The identifier for the shape within a Box2D world.
Returns
number: The density value of the specified shape.

b2Shape_SetFriction

Sets a new friction value for the specified shape. The operation will not proceed if the physics world is locked. The friction parameter must be a valid number greater than or equal to zero.

b2Shape_SetFriction(shapeId: b2ShapeId, friction: number): void
Parameters
shapeId (b2ShapeId) The identifier for the shape to modify
friction (number) The friction coefficient value (must be >= 0)
Returns
void:
Throws
  • Error: Throws an assertion error if friction is invalid or negative
  • Error: Throws an assertion error if the world is locked

b2Shape_GetFriction

Retrieves the friction value from a shape object in the Box2D physics world using the provided shape identifier.

b2Shape_GetFriction(shapeId: b2ShapeId): number
Parameters
shapeId (b2ShapeId) The identifier for the shape in the physics world.
Returns
number: The friction coefficient of the shape.

b2Shape_SetRestitution

Sets the restitution (bounciness) value for a shape.

b2Shape_SetRestitution(shapeId: b2ShapeId, restitution: number): void
Parameters
shapeId (b2ShapeId) The identifier for the shape to modify.
restitution (number) The restitution value to set. Must be non-negative.
Returns
void:
Throws
  • Error: Throws an assertion error if restitution is invalid or negative, or if the world is locked.

b2Shape_GetRestitution

Retrieves the restitution (bounciness) value associated with the specified shape from the physics world.

b2Shape_GetRestitution(shapeId: b2ShapeId): number
Parameters
shapeId (b2ShapeId) The identifier for the shape in the physics world.
Returns
number: The restitution coefficient of the shape.

b2Shape_GetFilter

Retrieves the collision filtering data from a shape by first accessing the world object using the world identifier stored in the shapeId, then accessing the shape within that world using the shapeId.

b2Shape_GetFilter(shapeId: b2ShapeId): b2Filter
Parameters
shapeId (b2ShapeId) The identifier for the shape.
Returns
b2Filter: The collision filter data associated with the shape.

b2Shape_SetFilter

Updates the collision filter properties of a shape. If the new filter settings match the existing ones, no changes are made. When the categoryBits change, the shape's broad-phase proxy is destroyed and recreated. The function also wakes connected bodies when the filter changes.

b2Shape_SetFilter(shapeId: b2ShapeId, filter: b2Filter): void
Parameters
shapeId (b2ShapeId) The identifier for the shape to modify.
filter (b2Filter) The new collision filter settings to apply.
Returns
void:

b2Shape_EnableSensorEvents

Sets the enableSensorEvents property of a shape in the physics world. The shape must exist in a valid world context for the operation to succeed.

b2Shape_EnableSensorEvents(shapeId: b2ShapeId, flag: boolean): void
Parameters
shapeId (b2ShapeId) The identifier of the shape to modify.
flag (boolean) True to enable sensor events, false to disable them.
Returns
void:

b2Shape_AreSensorEventsEnabled

This function retrieves a shape from the physics world using its ID and returns the state of its sensor events flag.

b2Shape_AreSensorEventsEnabled(shapeId: b2ShapeId): boolean
Parameters
shapeId (b2ShapeId) The identifier for the shape to check.
Returns
boolean: True if sensor events are enabled for the shape, false otherwise.

b2Shape_EnableContactEvents

Sets whether a shape should generate contact events during collision detection. The shape must belong to a valid world, otherwise the function returns without effect.

b2Shape_EnableContactEvents(shapeId: b2ShapeId, flag: boolean): void
Parameters
shapeId (b2ShapeId) The identifier for the shape.
flag (boolean) True to enable contact events, false to disable.
Returns
void:

b2Shape_AreContactEventsEnabled

This function retrieves a shape from the physics world using its ID and checks the enableContactEvents property of that shape.

b2Shape_AreContactEventsEnabled(shapeId: b2ShapeId): boolean
Parameters
shapeId (b2ShapeId) The identifier for the shape to check.
Returns
boolean: True if contact events are enabled for the shape, false otherwise.

b2Shape_EnablePreSolveEvents

Enables or disables pre-solve events for a specific shape in the physics simulation. The function first validates the world reference and returns if invalid. If valid, it updates the shape's pre-solve events setting according to the flag parameter.

b2Shape_EnablePreSolveEvents(shapeId: b2ShapeId, flag: boolean): void
Parameters
shapeId (b2ShapeId) The identifier for the shape in the physics world
flag (boolean) Boolean value to enable or disable pre-solve events for the shape
Returns
void:

b2Shape_ArePreSolveEventsEnabled

This function retrieves a shape from the physics world using its ID and checks the enablePreSolveEvents property of that shape.

b2Shape_ArePreSolveEventsEnabled(shapeId: b2ShapeId): boolean
Parameters
shapeId (b2ShapeId) The identifier for the shape to check.
Returns
boolean: True if pre-solve events are enabled for the shape, false otherwise.

b2Shape_EnableHitEvents

Sets whether a shape should generate hit events during collision detection. The shape must belong to a valid world, otherwise the function returns without effect.

b2Shape_EnableHitEvents(shapeId: b2ShapeId, flag: boolean): void
Parameters
shapeId (b2ShapeId) The identifier of the shape to modify.
flag (boolean) True to enable hit events, false to disable.
Returns
void:
Throws
  • Error: If the world associated with the shapeId is locked.

b2Shape_AreHitEventsEnabled

This function retrieves a shape from the physics world using its ID and checks if hit events are enabled for that shape by accessing the enableHitEvents property.

b2Shape_AreHitEventsEnabled(shapeId: b2ShapeId): boolean
Parameters
shapeId (b2ShapeId) The identifier for the shape to check.
Returns
boolean: True if hit events are enabled for the shape, false otherwise.

b2Shape_GetType

Retrieves a shape from the physics world using the provided shape ID and returns its type classification.

b2Shape_GetType(shapeId: b2ShapeId): b2ShapeType
Parameters
shapeId (b2ShapeId) The ID of the shape to query
Returns
b2ShapeType: The type of the specified shape

b2Shape_GetCircle

Retrieves a circle shape from the physics world using the provided shape identifier.

b2Shape_GetCircle(shapeId: b2ShapeId): b2Circle
Parameters
shapeId (b2ShapeId) A shape identifier containing world and shape reference
Returns
b2Circle: The circle shape object
Throws
  • Error: Throws an assertion error if the shape type is not b2_circleShape

b2Shape_GetSegment

Retrieves the segment data from a shape in the physics world. The shape must be of type b2_segmentShape.

b2Shape_GetSegment(shapeId: b2ShapeId): b2Segment
Parameters
shapeId (b2ShapeId) A shape identifier containing world and shape reference
Returns
b2Segment: The segment data from the specified shape
Throws
  • Error: Throws an assertion error if the shape type is not b2_segmentShape

b2Shape_GetChainSegment

Gets the chain segment data from a shape identified by its ID.

b2Shape_GetChainSegment(shapeId: Object): Object
Parameters
shapeId (Object) An object containing the shape identifier and world reference.
Name Description
shapeId.world0 number The world identifier.
Returns
Object: The chain segment data associated with the shape.
Throws
  • Error: Throws an assertion error if the shape type is not b2_chainSegmentShape.

b2Shape_GetCapsule

Retrieves the capsule shape data from a shape in the physics world using the provided shape ID.

b2Shape_GetCapsule(shapeId: b2ShapeId): b2Capsule
Parameters
shapeId (b2ShapeId) A shape identifier containing world and shape reference information
Returns
b2Capsule: The capsule shape data associated with the given shape ID
Throws
  • Error: Throws an assertion error if the shape type is not b2_capsuleShape

b2Shape_GetPolygon

Gets a polygon shape from a shape ID.

b2Shape_GetPolygon(shapeId: b2ShapeId): b2Polygon
Parameters
shapeId (b2ShapeId) The ID of the shape to retrieve.
Returns
b2Polygon: The polygon shape associated with the given shape ID.
Throws
  • Error: Throws an assertion error if the shape type is not b2_polygonShape.

b2Shape_SetCircle

Sets a shape's type to circle and updates its properties. The function updates the shape's proxy in the broad-phase collision system and can wake connected bodies. If the world is locked or invalid, the function returns without making changes.

b2Shape_SetCircle(shapeId: b2ShapeId, circle: b2Circle): void
Parameters
shapeId (b2ShapeId) The identifier for the shape to be modified
circle (b2Circle) The circle shape configuration to set
Returns
void:

b2Shape_SetCapsule

Sets a shape's type to capsule and updates its configuration. The function resets the shape's proxy in the broad-phase collision system, optionally waking connected bodies and destroying the existing proxy.

b2Shape_SetCapsule(shapeId: b2ShapeId, capsule: b2Capsule): void
Parameters
shapeId (b2ShapeId) The identifier for the shape to be modified
capsule (b2Capsule) The capsule shape configuration to set
Returns
void:
Throws
  • Error: If the world reference is invalid (null)

b2Shape_SetSegment

Sets a shape's type to segment and updates its segment data. After updating, it resets the shape's collision proxy in the physics world. The function requires a valid world lock to execute successfully.

b2Shape_SetSegment(shapeId: b2ShapeId, segment: b2Segment): void
Parameters
shapeId (b2ShapeId) The identifier for the shape to be modified
segment (b2Segment) The segment data to assign to the shape
Returns
void:

b2Shape_SetPolygon

Sets a shape's type to polygon and assigns polygon data to it. The function updates the shape's proxy in the broad-phase collision system and can wake connected bodies.

b2Shape_SetPolygon(shapeId: b2ShapeId, polygon: b2Polygon): void
Parameters
shapeId (b2ShapeId) The identifier for the shape to be modified
polygon (b2Polygon) The polygon data to assign to the shape
Returns
void:
Throws
  • Error: If the world associated with the shapeId is not found

b2Shape_GetParentChain

Retrieves the parent chain identifier for a given shape if it is a chain segment shape and has an associated chain. The function checks if the shape is of type b2_chainSegmentShape and has a valid chain reference before returning the chain identifier.

b2Shape_GetParentChain(shapeId: b2ShapeId): b2ChainId
Parameters
shapeId (b2ShapeId) The identifier of the shape to check for parent chain
Returns
b2ChainId: A b2ChainId object. Returns an empty b2ChainId (default values) if the shape is not a chain segment shape or has no parent chain

b2Chain_SetFriction

Updates the friction property of each shape within the specified chain. The function retrieves the chain shape from the world, then iterates through all shapes in the chain and sets their friction to the specified value.

b2Chain_SetFriction(chainId: b2ChainId, friction: number): void
Parameters
chainId (b2ChainId) The identifier for the chain whose friction will be modified
friction (number) The friction value to set for all shapes in the chain
Returns
void:

b2Chain_SetRestitution

Sets the restitution coefficient for all shapes that make up the specified chain. If the world is not found using the provided chainId, the function returns without making changes.

b2Chain_SetRestitution(chainId: b2ChainId, restitution: number): void
Parameters
chainId (b2ChainId) The identifier for the chain whose restitution will be set
restitution (number) The restitution value to apply to all shapes in the chain
Returns
void:

b2Shape_GetContactCapacity

Retrieves the number of contacts associated with the body that owns the specified shape. If the shape is a sensor or the world reference is invalid, the function returns 0.

b2Shape_GetContactCapacity(shapeId: b2ShapeId): number
Parameters
shapeId (b2ShapeId) The identifier for the shape to check
Returns
number: The number of contacts for the shape's body. Returns 0 if the world is invalid, or if the shape is a sensor.

b2Shape_GetContactData

Retrieves contact data for a specified shape. For each valid contact involving the shape, stores the shape IDs of both bodies in contact and their contact manifold. Only stores contacts where the touching flag is set and ignores sensor shapes.

b2Shape_GetContactData(shapeId: b2ShapeId, contactData: Array<{shapeIdA: b2ShapeId, shapeIdB: b2ShapeId, manifold: b2Manifold}>, capacity: number): number
Parameters
shapeId (b2ShapeId) The identifier of the shape to get contact data for
contactData (Array<{shapeIdA: b2ShapeId, shapeIdB: b2ShapeId, manifold: b2Manifold}>) Array to store the contact data
capacity (number) Maximum number of contacts to retrieve
Returns
number: The number of contacts found and stored in contactData
Throws
  • Error: If the world is locked or invalid

b2Shape_GetAABB

Retrieves the Axis-Aligned Bounding Box (AABB) associated with a shape in the physics world. If the world reference is invalid, returns a default AABB with zero dimensions.

b2Shape_GetAABB(shapeId: b2ShapeId): b2AABB
Parameters
shapeId (b2ShapeId) The identifier for the shape.
Returns
b2AABB: The AABB of the shape. Returns an empty AABB if the world is null.

b2Shape_GetClosestPoint

Calculates the closest point on a shape to a given target point, taking into account the shape's position and rotation in world space. Uses the distance calculation algorithm with shape proxies and transforms.

b2Shape_GetClosestPoint(shapeId: b2ShapeId, target: b2Vec2): b2Vec2
Parameters
shapeId (b2ShapeId) ID of the shape to query
target (b2Vec2) The target point to find the closest point to
Returns
b2Vec2: The closest point on the shape to the target point. Returns (0,0) if the world is invalid.

Types

Types

Types

b2DefaultWorldDef

Initializes a new b2WorldDef with default values suitable for standard physics simulations. All distance-based values are scaled by b2_lengthUnitsPerMeter2.

b2DefaultWorldDef(): b2WorldDef
Returns
b2WorldDef: A world definition object with the following properties:
  • gravity: {b2Vec2} Set to (0, -10)
  • hitEventThreshold: {number} Set to 1 meter
  • restitutionThreshold: {number} Set to 10 meters
  • contactPushoutVelocity: {number} Set to 5 meters
  • contactHertz: {number} Set to 30
  • contactDampingRatio: {number} Set to 10
  • jointHertz: {number} Set to 60
  • jointDampingRatio: {number} Set to 5
  • maximumLinearVelocity: {number} Set to 400 meters
  • enableSleep: {boolean} Set to true
  • enableContinuous: {boolean} Set to true

b2DefaultBodyDef

Creates a new b2BodyDef with default values.

b2DefaultBodyDef(): b2BodyDef
Returns
b2BodyDef: A body definition object with the following default properties:
  • type: b2_staticBody
  • position: (0,0)
  • rotation: (cos=1, sin=0)
  • linearVelocity: (0,0)
  • angularVelocity: 0
  • linearDamping: 0
  • angularDamping: 0
  • gravityScale: 1
  • sleepThreshold: 0.05 * b2_lengthUnitsPerMeter2
  • userData: null
  • enableSleep: true
  • isAwake: true
  • fixedRotation: false
  • isBullet: false
  • isEnabled: true
  • updateBodyMass: true
  • allowFastRotation: false

b2DefaultFilter

Creates and returns a new b2Filter object initialized with default values for collision filtering. The categoryBits determine what collision category this object belongs to, the maskBits determine what categories this object can collide with, and the groupIndex determines collision groups (negative values mean never collide, positive values mean always collide with same group).

b2DefaultFilter(): b2Filter
Returns
b2Filter: A filter object with categoryBits=1, maskBits=4294967295 (0xFFFFFFFF), and groupIndex=0

b2DefaultQueryFilter

This function instantiates a new b2QueryFilter with default collision filtering settings. The categoryBits value of 1 represents the default category, while the maskBits value of 4294967295 allows collision with all categories.

b2DefaultQueryFilter(): b2QueryFilter
Returns
b2QueryFilter: A query filter object with categoryBits set to 1 and maskBits set to 4294967295 (0xFFFFFFFF).

b2DefaultShapeDef

This function initializes a new b2ShapeDef object with commonly used physics properties. The shape definition can be used to create various types of physics shapes in Box2D.

b2DefaultShapeDef(): b2ShapeDef
Returns
b2ShapeDef: A shape definition object with the following default values:
  • friction: 0.6
  • density: 1
  • restitution: 0.1
  • filter: default collision filter
  • enableSensorEvents: true
  • enableContactEvents: true

b2DefaultChainDef

Initializes a new chain definition with common default values. The chain shape represents a series of connected line segments.

b2DefaultChainDef(): b2ChainDef
Returns
b2ChainDef: A chain definition object with:
  • friction set to 0.6
  • default filter settings
  • all other properties at their default values

b2RayResult

Result from b2World_RayCastClosest

new b2RayResult()
Properties
shapeId (b2ShapeId) : The shape that was hit
point (b2Vec2) : The hit point
normal (b2Vec2) : The hit normal
fraction (number) : The hit fraction along the ray
nodeVisits (number) : Number of tree nodes visited
leafVisits (number) : Number of tree leaves visited
hit (boolean) : Whether the ray hit anything

b2WorldDef

TYPES

b2WorldDef

b2WorldDef

TYPES

b2WorldDef

b2WorldDef

new b2WorldDef()
Properties
gravity (b2Vec2) : Gravity vector. Box2D has no up-vector defined.
restitutionThreshold (number) : Restitution velocity threshold, usually in m/s. Collisions above this speed have restitution applied (will bounce).
contactPushoutVelocity (number) : This parameter controls how fast overlap is resolved and has units of meters per second
hitEventThreshold (number) : Threshold velocity for hit events. Usually meters per second.
contactHertz (number) : Contact stiffness. Cycles per second.
contactDampingRatio (number) : Contact bounciness. Non-dimensional.
jointHertz (number) : Joint stiffness. Cycles per second.
jointDampingRatio (number) : Joint bounciness. Non-dimensional.
maximumLinearVelocity (number) : Maximum linear velocity. Usually meters per second.
frictionMixingRule (b2MixingRule) : Mixing rule for friction. Default is b2_mixGeometricMean.
restitutionMixingRule (b2MixingRule) : Mixing rule for restitution. Default is b2_mixMaximum.
enableSleep (boolean) : Can bodies go to sleep to improve performance
enableContinuous (boolean) : Enable continuous collision
workerCount (number) : Number of workers to use with the provided task system.
enqueueTask (Function) : Function to spawn tasks
finishTask (Function) : Function to finish a task
userTaskContext (any) : User context that is provided to enqueueTask and finishTask
userData (any) : User data
internalValue (number) : Used internally to detect a valid definition. DO NOT SET.

b2BodyDef

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2BodyDef

b2BodyDef

new b2BodyDef()
Properties
type (b2BodyType) : The body type: static, kinematic, or dynamic
position (b2Vec2) : The initial world position of the body
rotation (b2Rot) : The initial world rotation of the body
linearVelocity (b2Vec2) : The initial linear velocity in meters per second
angularVelocity (number) : The initial angular velocity in radians per second
linearDamping (number) : Linear damping to reduce linear velocity
angularDamping (number) : Angular damping to reduce angular velocity
gravityScale (number) : Scale factor applied to gravity for this body
sleepThreshold (number) : Sleep velocity threshold, default 0.05 m/s
userData (any) : Application specific body data
enableSleep (boolean) : Whether this body can fall asleep
isAwake (boolean) : Whether body starts awake or sleeping
fixedRotation (boolean) : Whether to prevent rotation
isBullet (boolean) : Whether to use continuous collision detection
isEnabled (boolean) : Whether body can move and collide
allowFastRotation (boolean) : Whether to bypass rotation speed limits
internalValue (number) : Internal validation flag

b2ShapeDef

new b2ShapeDef()
Properties
userData (any) : Use this to store application specific shape data
friction (number) : The Coulomb (dry) friction coefficient, usually in the range [0,1]
restitution (number) : The restitution (bounce) usually in the range [0,1]
density (number) : The density, usually in kg/m^2
filter (b2Filter) : Collision filtering data
customColor (number) : Custom debug draw color
isSensor (boolean) : A sensor shape generates overlap events but never generates a collision response
enableSensorEvents (boolean) : Enable sensor events for this shape. Only applies to kinematic and dynamic bodies
enableContactEvents (boolean) : Enable contact events for this shape. Only applies to kinematic and dynamic bodies
enableHitEvents (boolean) : Enable hit events for this shape. Only applies to kinematic and dynamic bodies
enablePreSolveEvents (boolean) : Enable pre-solve contact events for this shape. Only applies to dynamic bodies
invokeContactCreation (boolean) : Override static body behavior to force contact creation
updateBodyMass (boolean) : Should the body update mass properties when shape is created
internalValue (number) : Used internally to detect a valid definition. DO NOT SET

b2ChainDef

new b2ChainDef()
Properties
userData (void) : Use this to store application specific shape data
points (Array<b2Vec2>) : Array of at least 4 points defining the chain segments
count (number) : The point count, must be 4 or more
friction (number) : The friction coefficient, usually in the range [0,1]
restitution (number) : The restitution (elasticity) usually in the range [0,1]
filter (b2Filter) : Contact filtering data
customColor (number) : Custom debug draw color
isLoop (boolean) : Indicates a closed chain formed by connecting first and last points
internalValue (number) : Used internally to detect valid definition. DO NOT SET

b2DistanceJointDef

This requires defining an anchor point on both bodies and the non-zero distance of the distance joint. The definition uses local anchor points so that the initial configuration can violate the constraint slightly. This helps when saving and loading a game.

new b2DistanceJointDef()
Properties
bodyIdA (b2BodyId) : The first attached body
bodyIdB (b2BodyId) : The second attached body
localAnchorA (b2Vec2) : The local anchor point relative to bodyA's origin
localAnchorB (b2Vec2) : The local anchor point relative to bodyB's origin
length (number) : The rest length of this joint. Clamped to a stable minimum value.
enableSpring (boolean) : Enable the distance constraint to behave like a spring. If false then the distance joint will be rigid, overriding the limit and motor.
hertz (number) : The spring linear stiffness Hertz, cycles per second
dampingRatio (number) : The spring linear damping ratio, non-dimensional
enableLimit (boolean) : Enable/disable the joint limit
minLength (number) : Minimum length. Clamped to a stable minimum value.
maxLength (number) : Maximum length. Must be greater than or equal to the minimum length.
enableMotor (boolean) : Enable/disable the joint motor
maxMotorForce (number) : The maximum motor force, usually in newtons
motorSpeed (number) : The desired motor speed, usually in meters per second
collideConnected (boolean) : Set this flag to true if the attached bodies should collide
userData (any) : User data pointer
internalValue (number) : Used internally to detect a valid definition. DO NOT SET.

b2MotorJointDef

new b2MotorJointDef()
Properties
bodyIdA (b2BodyId) : The first attached body
bodyIdB (b2BodyId) : The second attached body
linearOffset (b2Vec2) : Position of bodyB minus the position of bodyA, in bodyA's frame
angularOffset (number) : The bodyB angle minus bodyA angle in radians
maxForce (number) : The maximum motor force in newtons
maxTorque (number) : The maximum motor torque in newton-meters
correctionFactor (number) : Position correction factor in the range [0,1]
collideConnected (boolean) : Set this flag to true if the attached bodies should collide
userData (any) : User data pointer
internalValue (number) : Used internally to detect a valid definition. DO NOT SET.

b2MouseJointDef

new b2MouseJointDef()
Properties
bodyIdA (b2BodyId) : The first attached body
bodyIdB (b2BodyId) : The second attached body
target (b2Vec2) : The initial target point in world space
hertz (number) : Stiffness in hertz
dampingRatio (number) : Damping ratio, non-dimensional
maxForce (number) : Maximum force, typically in newtons
collideConnected (boolean) : Set this flag to true if the attached bodies should collide
userData (any) : User data pointer
internalValue (number) : Used internally to detect a valid definition. DO NOT SET.

b2PrismaticJointDef

new b2PrismaticJointDef()
Properties
bodyIdA (b2BodyId) : The first attached body
bodyIdB (b2BodyId) : The second attached body
localAnchorA (b2Vec2) : The local anchor point relative to bodyA's origin
localAnchorB (b2Vec2) : The local anchor point relative to bodyB's origin
localAxisA (b2Vec2) : The local translation unit axis in bodyA
referenceAngle (number) : The constrained angle between the bodies: bodyB_angle - bodyA_angle
enableSpring (boolean) : Enable a linear spring along the prismatic joint axis
hertz (number) : The spring stiffness Hertz, cycles per second
dampingRatio (number) : The spring damping ratio, non-dimensional
enableLimit (boolean) : Enable/disable the joint limit
lowerTranslation (number) : The lower translation limit
upperTranslation (number) : The upper translation limit
enableMotor (boolean) : Enable/disable the joint motor
maxMotorForce (number) : The maximum motor force, typically in newtons
motorSpeed (number) : The desired motor speed, typically in meters per second
collideConnected (boolean) : Set this flag to true if the attached bodies should collide
userData (any) : User data pointer
internalValue (number) : Used internally to detect a valid definition. DO NOT SET.

b2RevoluteJointDef

new b2RevoluteJointDef()
Properties
bodyIdA (b2BodyId) : The first attached body
bodyIdB (b2BodyId) : The second attached body
localAnchorA (b2Vec2) : The local anchor point relative to bodyA's origin
localAnchorB (b2Vec2) : The local anchor point relative to bodyB's origin
referenceAngle (number) : The bodyB angle minus bodyA angle in the reference state (radians)
enableSpring (boolean) : Enable a rotational spring on the revolute hinge axis
hertz (number) : The spring stiffness Hertz, cycles per second
dampingRatio (number) : The spring damping ratio, non-dimensional
enableLimit (boolean) : A flag to enable joint limits
lowerAngle (number) : The lower angle for the joint limit in radians
upperAngle (number) : The upper angle for the joint limit in radians
enableMotor (boolean) : A flag to enable the joint motor
maxMotorTorque (number) : The maximum motor torque, typically in newton-meters
motorSpeed (number) : The desired motor speed in radians per second
drawSize (number) : Scale the debug draw
collideConnected (boolean) : Set this flag to true if the attached bodies should collide
userData (any) : User data pointer
internalValue (number) : Used internally to detect a valid definition. DO NOT SET.

b2WeldJointDef

new b2WeldJointDef()
Properties
bodyIdA (b2BodyId) : The first attached body
bodyIdB (b2BodyId) : The second attached body
localAnchorA (b2Vec2) : The local anchor point relative to bodyA's origin
localAnchorB (b2Vec2) : The local anchor point relative to bodyB's origin
referenceAngle (number) : The bodyB angle minus bodyA angle in the reference state (radians)
linearHertz (number) : Linear stiffness expressed as Hertz (cycles per second). Use zero for maximum stiffness.
angularHertz (number) : Angular stiffness as Hertz (cycles per second). Use zero for maximum stiffness.
linearDampingRatio (number) : Linear damping ratio, non-dimensional. Use 1 for critical damping.
angularDampingRatio (number) : Linear damping ratio, non-dimensional. Use 1 for critical damping.
collideConnected (boolean) : Set this flag to true if the attached bodies should collide
userData (any) : User data pointer
internalValue (number) : Used internally to detect a valid definition. DO NOT SET.

b2WheelJointDef

new b2WheelJointDef()
Properties
bodyIdA (b2BodyId) : The first attached body
bodyIdB (b2BodyId) : The second attached body
localAnchorA (b2Vec2) : The local anchor point relative to bodyA's origin
localAnchorB (b2Vec2) : The local anchor point relative to bodyB's origin
localAxisA (b2Vec2) : The local translation unit axis in bodyA
enableSpring (boolean) : Enable a linear spring along the local axis
hertz (number) : Spring stiffness in Hertz
dampingRatio (number) : Spring damping ratio, non-dimensional
enableLimit (boolean) : Enable/disable the joint linear limit
lowerTranslation (number) : The lower translation limit
upperTranslation (number) : The upper translation limit
enableMotor (boolean) : Enable/disable the joint rotational motor
maxMotorTorque (number) : The maximum motor torque, typically in newton-meters
motorSpeed (number) : The desired motor speed in radians per second
collideConnected (boolean) : Set this flag to true if the attached bodies should collide
userData (any) : User data pointer
internalValue (number) : Used internally to detect a valid definition. DO NOT SET.

b2SensorBeginTouchEvent

new b2SensorBeginTouchEvent()
Properties
sensorShapeId (b2ShapeId) : The id of the sensor shape
visitorShapeId (b2ShapeId) : The id of the dynamic shape that began touching the sensor shape

b2SensorEndTouchEvent

new b2SensorEndTouchEvent()
Properties
sensorShapeId (b2ShapeId) : The id of the sensor shape
visitorShapeId (b2ShapeId) : The id of the dynamic shape that stopped touching the sensor shape

b2SensorEvents

new b2SensorEvents()
Properties
beginEvents (Array<b2SensorBeginTouchEvent>) : Array of sensor begin touch events
endEvents (Array<b2SensorEndTouchEvent>) : Array of sensor end touch events
beginCount (number) : The number of begin touch events
endCount (number) : The number of end touch events

b2ContactBeginTouchEvent

new b2ContactBeginTouchEvent()
Properties
shapeIdA (b2ShapeId) : Id of the first shape
shapeIdB (b2ShapeId) : Id of the second shape
manifold (b2Manifold) : The initial contact manifold

b2ContactEndTouchEvent

new b2ContactEndTouchEvent()
Properties
shapeIdA (b2ShapeId) : Id of the first shape
shapeIdB (b2ShapeId) : Id of the second shape

b2ContactHitEvent

new b2ContactHitEvent()
Properties
shapeIdA (b2ShapeId) : Id of the first shape
shapeIdB (b2ShapeId) : Id of the second shape
point (b2Vec2) : Point where the shapes hit
normal (b2Vec2) : Normal vector pointing from shape A to shape B
approachSpeed (number) : The speed the shapes are approaching. Always positive. Typically in meters per second.

b2ContactEvents

new b2ContactEvents()
Properties
beginEvents (Array<b2ContactBeginTouchEvent>) : Array of begin touch events
endEvents (Array<b2ContactEndTouchEvent>) : Array of end touch events
hitEvents (Array<b2ContactHitEvent>) : Array of hit events
beginCount (number) : Number of begin touch events
endCount (number) : Number of end touch events
hitCount (number) : Number of hit events

b2BodyMoveEvent

new b2BodyMoveEvent()
Properties
transform (b2Transform) : The new transform of the moved body
bodyId (b2BodyId) : The identifier of the moved body
userData (void) : User data associated with the body
fellAsleep (boolean) : Indicates if the body transitioned to sleep state

b2BodyEvents

new b2BodyEvents()
Properties
moveEvents (Array<b2BodyMoveEvent>) : Array of move events
moveCount (number) : Number of move events

b2ContactData

new b2ContactData()
Properties
shapeIdA (b2ShapeId) : The identifier for the first shape
shapeIdB (b2ShapeId) : The identifier for the second shape
manifold (b2Manifold) : The contact manifold between the shapes
Related
b2Shape_GetContactData() b2Body_GetContactData()

b2DebugDraw

new b2DebugDraw()
Properties
DrawString (function (b2Vec2, string, any): void) : Draw a string
drawingBounds (b2AABB) : Bounds to use if restricting drawing to a rectangular region
useDrawingBounds (boolean) : Option to restrict drawing to a rectangular region. May suffer from unstable depth sorting
drawShapes (boolean) : Option to draw shapes
drawJoints (boolean) : Option to draw joints
drawJointExtras (boolean) : Option to draw additional information for joints
drawAABBs (boolean) : Option to draw the bounding boxes for shapes
drawMass (boolean) : Option to draw the mass and center of mass of dynamic bodies
drawContacts (boolean) : Option to draw contact points
drawGraphColors (boolean) : Option to visualize the graph coloring used for contacts and joints
drawContactNormals (boolean) : Option to draw contact normals
drawContactImpulses (boolean) : Option to draw contact normal impulses
drawFrictionImpulses (boolean) : Option to draw contact friction impulses
context (any) : User context that is passed as an argument to drawing callback functions

b2Filter

new b2Filter()
Properties
categoryBits (number) : The collision category bits. Normally you would just set one bit. The category bits should represent your application object types.
maskBits (number) : The collision mask bits. States the categories that this shape would accept for collision.
groupIndex (number) : Collision groups allow a certain group of objects to never collide (negative) or always collide (positive). Zero has no effect. Non-zero group filtering always wins against the mask bits.

b2QueryFilter

new b2QueryFilter()
Properties
categoryBits (number) : The collision category bits of this query. Normally you would just set one bit.
maskBits (number) : The collision mask bits. This states the shape categories that this query would accept for collision.

WeldJoint

WeldJoint

WeldJoint

b2WeldJoint_SetLinearHertz

Sets the linear frequency (hertz) for a weld joint.

b2WeldJoint_SetLinearHertz(jointId: b2JointId, hertz: number): void
Parameters
jointId (b2JointId) The identifier for the weld joint to modify
hertz (number) The frequency in hertz (must be >= 0)
Returns
void:
Throws
  • Error: If the hertz value is invalid or negative

b2WeldJoint_GetLinearHertz

Gets the linear Hertz value from a weld joint.

b2WeldJoint_GetLinearHertz(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the weld joint.
Returns
number: The linear Hertz value of the weld joint.
Throws
  • Error: If the joint is not of type b2_weldJoint.

b2WeldJoint_SetLinearDampingRatio

Sets the linear damping ratio for a weld joint.

b2WeldJoint_SetLinearDampingRatio(jointId: b2JointId, dampingRatio: number): void
Parameters
jointId (b2JointId) The identifier for the weld joint to modify.
dampingRatio (number) The damping ratio value. Must be non-negative.
Returns
void:
Throws
  • Error: If dampingRatio is invalid or negative.

b2WeldJoint_GetLinearDampingRatio

Gets the linear damping ratio of a weld joint.

b2WeldJoint_GetLinearDampingRatio(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the weld joint.
Returns
number: The linear damping ratio of the weld joint.
Throws
  • Error: If the joint is not of type b2_weldJoint.

b2WeldJoint_SetAngularHertz

Sets the angular frequency (hertz) for a weld joint's angular spring-damper.

b2WeldJoint_SetAngularHertz(jointId: b2JointId, hertz: number): void
Parameters
jointId (b2JointId) The identifier for the weld joint to modify.
hertz (number) The angular frequency in Hertz (must be >= 0).
Returns
void:
Throws
  • Error: If the hertz value is invalid (NaN, negative, or infinity).
  • Error: If the joint is not a weld joint.

b2WeldJoint_GetAngularHertz

Gets the angular frequency (hertz) of a weld joint.

b2WeldJoint_GetAngularHertz(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the weld joint.
Returns
number: The angular frequency in hertz.
Throws
  • Error: If the joint is not of type b2_weldJoint.

b2WeldJoint_SetAngularDampingRatio

Sets the angular damping ratio for a weld joint.

b2WeldJoint_SetAngularDampingRatio(jointId: b2JointId, dampingRatio: number): void
Parameters
jointId (b2JointId) The identifier for the weld joint to modify.
dampingRatio (number) The angular damping ratio. Must be non-negative.
Returns
void:
Throws
  • Error: If dampingRatio is invalid or negative.

b2WeldJoint_GetAngularDampingRatio

Gets the angular damping ratio of a weld joint.

b2WeldJoint_GetAngularDampingRatio(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier of the weld joint.
Returns
number: The angular damping ratio of the weld joint.
Throws
  • Error: Throws an error if the joint is not of type b2_weldJoint.

WheelJoint

WheelJoint

WheelJoint

b2WheelJoint_EnableSpring

Enables or disables the spring functionality of a wheel joint. When the spring state changes, the spring impulse is reset to zero.

b2WheelJoint_EnableSpring(jointId: b2JointId, enableSpring: boolean): void
Parameters
jointId (b2JointId) The identifier for the wheel joint to modify
enableSpring (boolean) True to enable the spring, false to disable it
Returns
void:
Throws
  • Error: If the joint identified by jointId is not a wheel joint

b2WheelJoint_IsSpringEnabled

b2WheelJoint_IsSpringEnabled(jointId: b2JointId): boolean
Parameters
jointId (b2JointId) The identifier for the wheel joint to check.
Returns
boolean: True if the spring is enabled, false otherwise.
Throws
  • Error: Throws if the joint is not a wheel joint type.

b2WheelJoint_SetSpringHertz

Sets the spring frequency for a wheel joint's oscillation. The frequency is specified in Hertz (Hz). The joint must be of type b2_wheelJoint.

b2WheelJoint_SetSpringHertz(jointId: b2JointId, hertz: number): void
Parameters
jointId (b2JointId) The identifier for the wheel joint to modify.
hertz (number) The spring frequency in Hertz (Hz).
Returns
void:
Throws
  • Error: Throws an error if the joint is not of type b2_wheelJoint.

b2WheelJoint_GetSpringHertz

Gets the spring frequency in Hertz for a wheel joint.

b2WheelJoint_GetSpringHertz(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the wheel joint.
Returns
number: The spring frequency in Hertz.
Throws
  • Error: If the joint is not a wheel joint type.

b2WheelJoint_SetSpringDampingRatio

Sets the damping ratio for a wheel joint's spring.

b2WheelJoint_SetSpringDampingRatio(jointId: b2JointId, dampingRatio: number): void
Parameters
jointId (b2JointId) The identifier for the wheel joint to modify
dampingRatio (number) The damping ratio for the spring (0 = no damping, 1 = critical damping)
Returns
void:
Throws
  • Error: If the joint is not a wheel joint type

b2WheelJoint_GetSpringDampingRatio

Gets the damping ratio of a wheel joint's spring.

b2WheelJoint_GetSpringDampingRatio(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the wheel joint.
Returns
number: The spring damping ratio value.
Throws
  • Error: Throws if the joint is not a wheel joint type.

b2WheelJoint_EnableLimit

Sets whether the wheel joint's translation limit is active. When the limit is enabled, the joint's translation will be constrained. When the limit state changes, the joint's lower and upper impulses are reset to zero.

b2WheelJoint_EnableLimit(jointId: b2JointId, enableLimit: boolean): void
Parameters
jointId (b2JointId) The identifier for the wheel joint.
enableLimit (boolean) True to enable the translation limit, false to disable it.
Returns
void:
Throws
  • Error: Throws if the joint is not a wheel joint type.

b2WheelJoint_IsLimitEnabled

b2WheelJoint_IsLimitEnabled(jointId: b2JointId): boolean
Parameters
jointId (b2JointId) The identifier for the wheel joint to check.
Returns
boolean: True if the limit is enabled, false otherwise.
Throws
  • Error: Throws if the joint is not a wheel joint.

b2WheelJoint_GetLowerLimit

Gets the lower translation limit of a wheel joint.

b2WheelJoint_GetLowerLimit(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the wheel joint.
Returns
number: The lower translation limit of the wheel joint.
Throws
  • Error: If the joint is not a wheel joint or the jointId is invalid.

b2WheelJoint_GetUpperLimit

Gets the upper translation limit of a wheel joint.

b2WheelJoint_GetUpperLimit(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the wheel joint.
Returns
number: The upper translation limit of the wheel joint.
Throws
  • Error: If the joint is not a wheel joint or the joint ID is invalid.

b2WheelJoint_SetLimits

Sets new translation limits for a wheel joint. The function automatically orders the limits so that the lower value is always less than or equal to the upper value. When the limits change, the joint's impulses are reset to zero.

b2WheelJoint_SetLimits(jointId: b2JointId, lower: number, upper: number): void
Parameters
jointId (b2JointId) The identifier for the wheel joint.
lower (number) The lower translation limit.
upper (number) The upper translation limit.
Returns
void:
Throws
  • Error: If the provided jointId does not reference a valid wheel joint.

b2WheelJoint_EnableMotor

Enables or disables the motor on a wheel joint. When the motor state changes, the motor impulse is reset to zero.

b2WheelJoint_EnableMotor(jointId: b2JointId, enableMotor: boolean): void
Parameters
jointId (b2JointId) The identifier for the wheel joint
enableMotor (boolean) True to enable the motor, false to disable it
Returns
void:
Throws
  • Error: If the joint is not a wheel joint type

b2WheelJoint_IsMotorEnabled

b2WheelJoint_IsMotorEnabled(jointId: b2JointId): boolean
Parameters
jointId (b2JointId) The identifier for the wheel joint to check.
Returns
boolean: True if the motor is enabled, false otherwise.
Throws
  • Error: Throws if the joint is not a wheel joint type.

b2WheelJoint_SetMotorSpeed

b2WheelJoint_SetMotorSpeed(jointId: b2JointId, motorSpeed: number): void
Parameters
jointId (b2JointId) The identifier for the wheel joint to modify.
motorSpeed (number) The desired motor speed in radians per second.
Returns
void:
Throws
  • Error: Throws if the joint is not a wheel joint type.

b2WheelJoint_GetMotorSpeed

Gets the motor speed of a wheel joint.

b2WheelJoint_GetMotorSpeed(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the wheel joint.
Returns
number: The current motor speed of the wheel joint in radians per second.
Throws
  • Error: If the joint is not a wheel joint type.

b2WheelJoint_GetMotorTorque

Calculates the motor torque by multiplying the motor impulse by the inverse of the time step. The joint must be of type b2_wheelJoint.

b2WheelJoint_GetMotorTorque(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the wheel joint.
Returns
number: The current motor torque normalized by the step time (Nâ‹…m).
Throws
  • Error: Throws if the joint type is not b2_wheelJoint.

b2WheelJoint_SetMaxMotorTorque

Sets the maximum torque that can be applied by the wheel joint's motor. The joint must be of type b2_wheelJoint.

b2WheelJoint_SetMaxMotorTorque(jointId: b2JointId, torque: number): void
Parameters
jointId (b2JointId) The identifier for the wheel joint.
torque (number) The maximum motor torque value to set.
Returns
void:
Throws
  • Error: Throws an error if the joint is not of type b2_wheelJoint.

b2WheelJoint_GetMaxMotorTorque

Gets the maximum motor torque of a wheel joint.

b2WheelJoint_GetMaxMotorTorque(jointId: b2JointId): number
Parameters
jointId (b2JointId) The identifier for the wheel joint.
Returns
number: The maximum motor torque value.
Throws
  • Error: If the joint is not a wheel joint type.

World

World

World

b2CreateWorldArray

Initializes a global array of Box2D world instances if it hasn't been created yet. Creates B2_MAX_WORLDS number of world instances and marks them as not in use. If the array already exists, the function returns without doing anything.

b2CreateWorldArray(): void
Returns
void:
Related
b2World

b2CreateWorld

Creates and initializes a new Box2D physics world with the specified parameters. The function allocates memory for physics entities (bodies, joints, contacts), initializes contact registers, creates necessary pools and arrays, and sets up the world properties according to the provided definition.

b2CreateWorld(def: b2WorldDef): b2WorldId
Parameters
def (b2WorldDef) World definition object containing initialization parameters including: gravity, hitEventThreshold, restitutionThreshold, maximumLinearVelocity, contactPushoutVelocity, contactHertz, contactDampingRatio, jointHertz, jointDampingRatio, enableSleep, enableContinuous
Returns
b2WorldId: A world identifier object containing:
  • index: number (worldId + 1)
  • revision: number (world revision number)
Throws
  • Error: Returns a null world ID (0,0) if no world slots are available

b2DestroyWorld

Destroys a Box2D world instance and all its associated resources, including debug sets, task contexts, event arrays, chains, bodies, shapes, contacts, joints, islands, solver sets, constraint graph, broad phase, ID pools, and stack allocator. Creates a new empty world instance with an incremented revision number.

b2DestroyWorld(worldId: b2WorldId): void
Parameters
worldId (b2WorldId) The ID of the world to destroy
Returns
void:
Throws
  • Error: Throws an assertion error if a null chain has non-null shape indices

b2World_Step

Performs one step of physics simulation by updating broad phase pairs, handling collisions, and solving the physics constraints. The function manages contact events, sensor events, and body movement events during the simulation step. It also handles warm starting and enforces velocity limits based on world settings.

b2World_Step(worldId: b2WorldId, timeStep: number, subStepCount: number): void
Parameters
worldId (b2WorldId) The identifier of the physics world to step
timeStep (number) The time increment to advance the simulation (in seconds)
subStepCount (number) The number of sub-steps to use for the iteration
Returns
void:
Throws
  • Error: Throws an assertion error if the world's stack allocator is not empty after the step completes.

b2World_Draw

Renders debug visualization of a Box2D world, including shapes, joints, AABBs, mass centers, and contact points based on the debug draw flags.

b2World_Draw(worldId: b2WorldId, draw: b2DebugDraw): void
Parameters
worldId (b2WorldId) ID of the Box2D world to render
draw (b2DebugDraw) Debug drawing context with rendering flags and methods
Returns
void:
Throws
  • Error: Throws assertion error if world is locked or body transform is null

b2World_GetBodyEvents

Retrieves the body movement events from a Box2D world. Returns an empty events object if the world is locked. The function copies the world's body move event array and count into a new b2BodyEvents object.

b2World_GetBodyEvents(worldId: b2WorldId): b2BodyEvents
Parameters
worldId (b2WorldId) The identifier for the Box2D world instance
Returns
b2BodyEvents: An object containing an array of body move events and their count
Throws
  • Error: Throws an assertion error if the world is locked

b2World_GetSensorEvents

Retrieves the sensor events from a Box2D world. The function returns both begin and end sensor events that occurred during the simulation step. If the world is locked, it returns an empty events object.

b2World_GetSensorEvents(worldId: b2WorldId): b2SensorEvents
Parameters
worldId (b2WorldId) The identifier of the Box2D world
Returns
b2SensorEvents: An object containing arrays of sensor begin and end events
Throws
  • Error: Throws an assertion error if the world is locked

b2World_GetContactEvents

Returns a b2ContactEvents object containing three arrays: contactBeginArray, contactEndArray, and contactHitArray, representing different types of contact events that occurred in the physics simulation. The object also includes count values for each type of event.

b2World_GetContactEvents(worldId: b2WorldId): b2ContactEvents
Parameters
worldId (b2WorldId) The identifier of the Box2D world.
Returns
b2ContactEvents: An object containing arrays of begin, end, and hit contact events, along with their respective counts.
Throws
  • Error: Throws an assertion error if the world is locked.

b2World_IsValid

Checks if a world ID is valid by verifying:

  1. The ID is not undefined
  2. The index is within valid bounds (1 to B2_MAX_WORLDS)
  3. The world exists at the specified index
  4. The revision number matches the world's current revision
b2World_IsValid(id: b2WorldId): boolean
Parameters
id (b2WorldId) The world identifier to validate, containing index1 and revision properties
Returns
boolean: True if the world ID is valid and matches the stored world revision, false otherwise

b2Body_IsValid

Performs validation checks on a body ID including:

  • Verifies the ID is defined and is a b2BodyId instance
  • Checks the world index is within valid bounds
  • Confirms the world exists and matches the ID
  • Validates the body index exists in the world
  • Ensures the body is active and the revision number matches
b2Body_IsValid(id: b2BodyId): boolean
Parameters
id (b2BodyId) The body ID to validate
Returns
boolean: True if the ID is valid and references an existing body, false otherwise

b2Shape_IsValid

Checks if a shape ID is valid by verifying:

  • The ID exists and is not undefined
  • The world index is within bounds
  • The referenced world exists and matches the world ID
  • The shape index is within bounds of the world's shape array
  • The shape exists and is not marked as null
  • The shape revision matches the ID's revision
b2Shape_IsValid(id: b2ShapeId): boolean
Parameters
id (b2ShapeId) The shape ID to validate, containing world0, index1, and revision properties
Returns
boolean: True if the shape ID is valid and references an existing shape, false otherwise

b2Chain_IsValid

Checks if a chain ID is valid by verifying:

  • The ID exists
  • The world index is within valid bounds
  • The world exists and matches the ID
  • The chain index is within valid bounds
  • The chain exists and is not null
  • The revision number matches
b2Chain_IsValid(id: b2ChainId): boolean
Parameters
id (b2ChainId) The chain identifier containing world0 (world index), index1 (chain index), and revision properties
Returns
boolean: Returns true if the chain ID is valid and matches the current revision, false otherwise

b2Joint_IsValid

Checks if a joint ID is valid by verifying:

  • The world index is within bounds
  • The referenced world exists and matches the ID
  • The joint index is within bounds
  • The joint exists and is not null
  • The revision number matches the joint's revision
b2Joint_IsValid(id: b2JointId): boolean
Parameters
id (b2JointId) The joint ID to validate, containing world0 (world index), index1 (joint index), and revision properties
Returns
boolean: True if the joint ID is valid and references an existing joint, false otherwise

b2World_EnableSleeping

Enables or disables the sleep management system for the specified Box2D world. When sleep is disabled, all sleeping bodies are awakened. The function has no effect if the world is locked or if the requested sleep state matches the current state.

b2World_EnableSleeping(worldId: b2WorldId, flag: boolean): void
Parameters
worldId (b2WorldId) The identifier of the Box2D world.
flag (boolean) When true, enables sleep management. When false, wakes all sleeping bodies.
Returns
void:
Throws
  • Error: Throws an assertion error if the world is locked.

b2World_EnableWarmStarting

Enables or disables warm starting for the specified Box2D world. Warm starting cannot be modified while the world is locked. If the world is locked when this function is called, the function will return without making any changes.

b2World_EnableWarmStarting(worldId: b2WorldId, flag: boolean): void
Parameters
worldId (b2WorldId) The identifier for the Box2D world instance
flag (boolean) Boolean value to enable or disable warm starting
Returns
void:
Throws
  • Error: Throws an assertion error if the world is locked

b2World_EnableContinuous

Sets the continuous collision detection state for the specified Box2D world. The function will not execute if the world is currently locked.

b2World_EnableContinuous(worldId: b2WorldId, flag: boolean): void
Parameters
worldId (b2WorldId) The identifier of the Box2D world.
flag (boolean) True to enable continuous collision detection, false to disable it.
Returns
void:
Throws
  • Error: Throws an assertion error if the world is locked when this function is called.

b2World_SetRestitutionThreshold

Sets the restitution threshold for collision response in the specified Box2D world. The value is clamped between 0 and Number.MAX_VALUE. The function will not execute if the world is locked.

b2World_SetRestitutionThreshold(worldId: b2WorldId, value: number): void
Parameters
worldId (b2WorldId) The identifier for the Box2D world.
value (number) The restitution threshold value to set.
Returns
void:
Throws
  • Error: Throws an assertion error if attempting to modify a locked world.

b2World_SetHitEventThreshold

Sets the hit event threshold for a Box2D world. The value is clamped between 0 and Number.MAX_VALUE. The function will not execute if the world is locked.

b2World_SetHitEventThreshold(worldId: b2WorldId, value: number): void
Parameters
worldId (b2WorldId) The identifier for the Box2D world instance
value (number) The new hit event threshold value to set
Returns
void:
Throws
  • Error: Throws an assertion error if the world is locked

b2World_SetContactTuning

Sets three contact-related parameters for physics simulation: the constraint frequency (hertz), damping ratio, and push-out velocity. All input parameters are clamped between 0 and MAX_VALUE. The function will not execute if the world is locked.

b2World_SetContactTuning(worldId: b2WorldId, hertz: number, dampingRatio: number, pushOut: number): void
Parameters
worldId (b2WorldId) The identifier for the Box2D world.
hertz (number) The frequency for contact constraint solving.
dampingRatio (number) The damping ratio for contact constraint solving.
pushOut (number) The velocity used for contact separation.
Returns
void:
Throws
  • Error: Throws an assertion error if attempting to modify a locked world.

b2World_OverlapAABB

Performs a broadphase query using the world's dynamic tree to find all fixtures that overlap with the given AABB. For each overlapping fixture that passes the filter, the callback function is invoked.

b2World_OverlapAABB(worldId: b2WorldId, aabb: b2AABB, filter: b2QueryFilter, fcn: b2OverlapResultFcn, context: any)
Parameters
worldId (b2WorldId) The ID of the physics world to query
aabb (b2AABB) The axis-aligned bounding box defining the query region
filter (b2QueryFilter) Filter settings to control which fixtures are included
fcn (b2OverlapResultFcn) Callback function that receives each overlapping fixture
context (any) User context data passed to the callback function
Throws
  • Error: Throws an assertion error if the world is locked or if the AABB is invalid

b2World_OverlapCircle

Performs broad-phase AABB queries to find potential overlaps between the given circle and all shapes in the world that match the filter criteria. For each potential overlap, the callback function is invoked with the overlap details.

b2World_OverlapCircle(worldId: b2WorldId, circle: b2Circle, transform: b2Transform, filter: b2QueryFilter, fcn: function, context: any)
Parameters
worldId (b2WorldId) The ID of the physics world
circle (b2Circle) The circle shape to test for overlaps
transform (b2Transform) The position and rotation transform of the circle
filter (b2QueryFilter) Filtering options for the overlap test
fcn (function) Callback function that handles overlap results
context (any) User context data passed to the callback function
Throws
  • Error: Throws an assertion error if the world is locked or if the transform contains invalid values.

b2World_OverlapCapsule

Tests a capsule shape against all shapes in the world that pass the filter criteria. For each potential overlap, calls the provided callback function. Uses a broad phase tree structure to efficiently find potential overlaps.

b2World_OverlapCapsule(worldId: b2WorldId, capsule: b2Capsule, transform: b2Transform, filter: b2QueryFilter, fcn: b2OverlapResultFcn, context: any)
Parameters
worldId (b2WorldId) The ID of the physics world
capsule (b2Capsule) The capsule shape to test for overlaps
transform (b2Transform) The position and rotation of the capsule
filter (b2QueryFilter) Filtering options for the query
fcn (b2OverlapResultFcn) Callback function that handles overlap results
context (any) User context data passed to the callback function
Throws
  • Error: Throws an assertion error if the world is locked or if the transform contains invalid position/rotation values.

b2World_OverlapPolygon

Performs overlap queries for a polygon shape against all shapes in the physics world that match the provided filter criteria.

b2World_OverlapPolygon(worldId: b2WorldId, polygon: b2Polygon, transform: b2Transform, filter: b2QueryFilter, fcn: b2OverlapResultFcn, context: void)
Parameters
worldId (b2WorldId) The identifier for the physics world
polygon (b2Polygon) The polygon shape to test for overlaps
transform (b2Transform) The position and rotation of the polygon
filter (b2QueryFilter) Filtering criteria for the overlap test
fcn (b2OverlapResultFcn) Callback function to handle overlap results
context (void) User data passed to the callback function
Throws
  • Error: Throws an assertion error if the world is locked or if the transform components are invalid

b2World_CastRay

Performs a ray cast operation in the physics world to detect intersections between a ray and physics bodies.

b2World_CastRay(worldId: b2WorldId, origin: b2Vec2, translation: b2Vec2, filter: b2QueryFilter, fcn: b2CastResultFcn, context: void): b2TreeStats
Parameters
worldId (b2WorldId) The ID of the physics world
origin (b2Vec2) The starting point of the ray
translation (b2Vec2) The direction and length of the ray
filter (b2QueryFilter) Filtering options for the ray cast
fcn (b2CastResultFcn) Callback function to handle ray cast results
context (void) User context data passed to the callback
Returns
b2TreeStats:
Throws
  • Error: Throws assertion error if world is locked
  • Error: Throws assertion error if origin or translation vectors are invalid

b2World_CastRayClosest

Casts a ray through the physics world and returns information about the closest intersection. The ray is defined by an origin point and a translation vector. The operation checks all body types in the broad phase using a dynamic tree structure.

b2World_CastRayClosest(worldId: b2WorldId, origin: b2Vec2, translation: b2Vec2, filter: b2QueryFilter): b2RayResult
Parameters
worldId (b2WorldId) The identifier for the physics world
origin (b2Vec2) The starting point of the ray
translation (b2Vec2) The direction and length of the ray
filter (b2QueryFilter) Filter settings for the ray cast
Returns
b2RayResult: Information about the closest intersection found
Throws
  • Error: Throws an assertion error if the world is locked or if the origin/translation vectors are invalid

b2World_CastCircle

Casts a circle shape through the physics world from its initial position along a translation vector, detecting collisions with other shapes. The cast is performed against all body types in the broad phase, stopping if a collision occurs at fraction 0.

b2World_CastCircle(worldId: b2WorldId, circle: b2Circle, originTransform: b2Transform, translation: b2Vec2, filter: b2QueryFilter, fcn: b2CastResultFcn, context: void)
Parameters
worldId (b2WorldId) The identifier for the physics world
circle (b2Circle) The circle shape to cast
originTransform (b2Transform) The initial transform of the circle
translation (b2Vec2) The displacement vector for the cast
filter (b2QueryFilter) Filtering options for the cast
fcn (b2CastResultFcn) Callback function to handle cast results
context (void) User data passed to the callback function
Throws
  • Error: Throws an assertion error if the world is locked or if the transform position, rotation, or translation vectors are invalid.

b2World_CastCapsule

Performs a shape cast of a capsule through the physics world, detecting collisions along the specified translation path.

b2World_CastCapsule(worldId: b2WorldId, capsule: b2Capsule, originTransform: b2Transform, translation: b2Vec2, filter: b2QueryFilter, fcn: b2CastResultFcn, context: void)
Parameters
worldId (b2WorldId) The identifier for the physics world
capsule (b2Capsule) The capsule shape to cast
originTransform (b2Transform) The initial transform of the capsule, containing position (p) and rotation (q)
translation (b2Vec2) The translation vector defining the cast path
filter (b2QueryFilter) Filter settings for the cast operation
fcn (b2CastResultFcn) Callback function to handle cast results
context (void) User context data passed to the callback function
Throws
  • Error: Throws assertion error if world is locked or if transform/translation vectors are invalid

b2World_CastPolygon

Performs a shape cast of a polygon through the physics world, detecting collisions along the way.

b2World_CastPolygon(worldId: b2WorldId, polygon: b2Polygon, originTransform: b2Transform, translation: b2Vec2, filter: b2QueryFilter, fcn: b2CastResultFcn, context: any)
Parameters
worldId (b2WorldId) ID of the physics world
polygon (b2Polygon) The polygon shape to cast
originTransform (b2Transform) Initial transform of the polygon, containing position and rotation
translation (b2Vec2) The displacement vector to cast the polygon along
filter (b2QueryFilter) Filter to determine which fixtures to check against
fcn (b2CastResultFcn) Callback function to handle cast results
context (any) User context data passed to the callback function
Throws
  • Error: Throws assertion error if world is locked or if transform/translation vectors are invalid

b2World_SetPreSolveCallback

Sets a callback function that is invoked before the physics solver runs. The callback receives the provided context pointer when executed.

b2World_SetPreSolveCallback(worldId: b2WorldId, fcn: b2PreSolveFcn, context: void): void
Parameters
worldId (b2WorldId) The identifier for the Box2D world instance
fcn (b2PreSolveFcn) The pre-solve callback function to be executed
context (void) User data pointer passed to the callback function
Returns
void:

b2World_SetCustomFilterCallback

Sets a custom filter callback function for a Box2D world instance. The callback can be used to implement custom collision filtering logic. The context parameter allows passing additional data to the callback function.

b2World_SetCustomFilterCallback(worldId: b2WorldId, fcn: b2CustomFilterFcn, context: void): void
Parameters
worldId (b2WorldId) The identifier for the Box2D world instance.
fcn (b2CustomFilterFcn) The custom filter callback function.
context (void) A pointer to user-defined context data.
Returns
void:

b2World_SetGravity

Updates the gravity vector of the specified Box2D world. The gravity vector defines the global acceleration applied to all dynamic bodies in the world.

b2World_SetGravity(worldId: b2WorldId, gravity: b2Vec2): void
Parameters
worldId (b2WorldId) The identifier for the Box2D world instance.
gravity (b2Vec2) The gravity vector to apply to the world. Defaults to (0,0).
Returns
void:

b2World_GetGravity

Retrieves the current gravity vector from the specified Box2D world instance. The gravity vector represents the global gravity force applied to all dynamic bodies in the world.

b2World_GetGravity(worldId: b2WorldId): b2Vec2
Parameters
worldId (b2WorldId) The identifier for the Box2D world instance.
Returns
b2Vec2: The gravity vector of the world. A 2D vector with x and y components.

b2World_Explode

Creates a circular explosion centered at the given position that applies radial forces to dynamic bodies within the explosion radius. The explosion force decreases with distance from the center point.

b2World_Explode(worldId: b2WorldId, position: b2Vec2, radius: number, magnitude: number): void
Parameters
worldId (b2WorldId) The ID of the Box2D world
position (b2Vec2) The center point of the explosion
radius (number) The radius of the explosion effect
magnitude (number) The force magnitude of the explosion
Returns
void:
Throws
  • Error: Throws assertion errors if:
    • position is invalid
    • radius is invalid or <= 0
    • magnitude is invalid
    • world is locked

b2World_GetProfile

This function returns performance profiling data for a Box2D world. Not supported in Phaser Box2D JS implementation.

b2World_GetProfile(worldId: b2WorldId): b2Profile
Parameters
worldId (b2WorldId) The identifier of the Box2D world.
Returns
b2Profile: A profile object containing performance metrics.
Throws
  • Error: Outputs a console warning indicating lack of support in Phaser Box2D JS.

b2World_GetCounters

This function is not supported in the Phaser Box2D JS implementation and will generate a console warning when called.

b2World_GetCounters(worldId: b2WorldId): b2Counters
Parameters
worldId (b2WorldId) The ID of the Box2D world instance.
Returns
b2Counters: An object containing various Box2D performance counters.

b2World_DumpMemoryStats

This function is a stub that displays a warning message indicating that memory statistics dumping is not supported in the Phaser Box2D JavaScript implementation.

b2World_DumpMemoryStats(worldId: b2WorldId): void
Parameters
worldId (b2WorldId) The identifier of the Box2D world
Returns
void:

b2World_DumpMemoryStats

This function is a stub that displays a warning message indicating that memory statistics dumping is not supported in the Phaser Box2D JavaScript implementation.

b2World_DumpMemoryStats(worldId: b2WorldId): void
Parameters
worldId (b2WorldId) The identifier of the Box2D world
Returns
void:

Base

b2Version

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
new b2Version(major: any, minor: any, revision: any)
Parameters
major (any = 0)
minor (any = 0)
revision (any = 0)

b2Version

new b2Version()
Properties
major (number) : Significant changes
minor (number) : Incremental changes
revision (number) : Bug fixes

b2Version

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Version

Collision

b2RayCastInput

new b2RayCastInput()
Properties
origin (b2Vec2) : Start point of the ray cast
translation (b2Vec2) : Translation of the ray cast
maxFraction (number) : The maximum fraction of the translation to consider, typically 1

b2ShapeCastInput

new b2ShapeCastInput()
Properties
points (Array<b2Vec2>) : A point cloud to cast
count (number) : The number of points
radius (number) : The radius around the point cloud
translation (b2Vec2) : The translation of the shape cast
maxFraction (number) : The maximum fraction of the translation to consider, typically 1

b2CastOutput

new b2CastOutput()
Properties
normal (b2Vec2) : The surface normal at the hit point
point (b2Vec2) : The surface hit point
fraction (number) : The fraction of the input translation at collision
iterations (number) : The number of iterations used
hit (boolean) : Did the cast hit?

b2MassData

new b2MassData()
Properties
mass (number) : The mass of the shape, usually in kilograms.
center (b2Vec2) : The position of the shape's centroid relative to the shape's origin.
rotationalInertia (number) : The rotational inertia of the shape about the local origin.

b2Circle

new b2Circle()
Properties
center (b2Vec2) : The local center
radius (number) : The radius

b2Capsule

new b2Capsule()
Properties
center1 (b2Vec2) : Local center of the first semicircle
center2 (b2Vec2) : Local center of the second semicircle
radius (number) : The radius of the semicircles

b2Polygon

new b2Polygon()
Properties
vertices (Array<b2Vec2>) : The polygon vertices
normals (Array<b2Vec2>) : The outward normal vectors of the polygon sides
centroid (b2Vec2) : The centroid of the polygon
radius (number) : The external radius for rounded polygons
count (number) : The number of polygon vertices

b2Segment

new b2Segment()
Properties
point1 (b2Vec2) : The first point
point2 (b2Vec2) : The second point

b2Hull

new b2Hull()
Properties
points (Array<b2Vec2>) : The final points of the hull
count (number) : The number of points

b2SegmentDistanceResult

new b2SegmentDistanceResult()
Properties
closest1 (b2Vec2) : The closest point on the first segment
closest2 (b2Vec2) : The closest point on the second segment
fraction1 (number) : The barycentric coordinate on the first segment
fraction2 (number) : The barycentric coordinate on the second segment
distanceSquared (number) : The squared distance between the closest points

b2DistanceProxy

new b2DistanceProxy()
Properties
points (Array<b2Vec2>) : The point cloud
count (number) : The number of points
radius (number) : The external radius of the point cloud

b2DistanceCache

new b2DistanceCache()
Properties
count (number) : The number of stored simplex points
indexA (Array<number>) : The cached simplex indices on shape A
indexB (Array<number>) : The cached simplex indices on shape B

b2DistanceInput

new b2DistanceInput()
Properties
proxyA (b2DistanceProxy) : The proxy for shape A
proxyB (b2DistanceProxy) : The proxy for shape B
transformA (b2Transform) : The world transform for shape A
transformB (b2Transform) : The world transform for shape B
useRadii (boolean) : Should the proxy radius be considered?

b2DistanceOutput

new b2DistanceOutput()
Properties
pointA (b2Vec2) : Closest point on shapeA
pointB (b2Vec2) : Closest point on shapeB
distance (number) : The final distance, zero if overlapped
iterations (number) : Number of GJK iterations used
simplexCount (number) : The number of simplexes stored in the simplex array

b2SimplexVertex

new b2SimplexVertex()
Properties
wA (b2Vec2) : Support point in proxyA
wB (b2Vec2) : Support point in proxyB
w (b2Vec2) : wB - wA
a (number) : Barycentric coordinate for closest point
indexA (number) : wA index
indexB (number) : wB index

b2Simplex

new b2Simplex()
Properties
v1 (b2SimplexVertex) : Simplex vertex
v2 (b2SimplexVertex) : Simplex vertex
v3 (b2SimplexVertex) : Simplex vertex
count (number) : Number of valid vertices

b2ShapeCastPairInput

new b2ShapeCastPairInput()
Properties
proxyA (b2DistanceProxy) : The proxy for shape A
proxyB (b2DistanceProxy) : The proxy for shape B
transformA (b2Transform) : The world transform for shape A
transformB (b2Transform) : The world transform for shape B
translationB (b2Vec2) : The translation of shape B
maxFraction (number) : The fraction of the translation to consider, typically 1

b2Sweep

new b2Sweep()
Properties
localCenter (b2Vec2) : Local center of mass position
c1 (b2Vec2) : Starting center of mass world position
c2 (b2Vec2) : Ending center of mass world position
q1 (b2Rot) : Starting world rotation
q2 (b2Rot) : Ending world rotation

b2TOIInput

new b2TOIInput()
Properties
proxyA (b2DistanceProxy) : The proxy for shape A
proxyB (b2DistanceProxy) : The proxy for shape B
sweepA (b2Sweep) : The movement of shape A
sweepB (b2Sweep) : The movement of shape B
tMax (number) : Defines the sweep interval [0, tMax]

b2TOIOutput

new b2TOIOutput()
Properties
state (b2TOIState) : The type of result
t (number) : The time of the collision

b2ManifoldPoint

new b2ManifoldPoint()
Properties
point (b2Vec2) : Location of the contact point in world space. Subject to precision loss at large coordinates. Should only be used for debugging.
anchorA (b2Vec2) : Location of the contact point relative to bodyA's origin in world space. When used internally to the Box2D solver, this is relative to the center of mass.
anchorB (b2Vec2) : Location of the contact point relative to bodyB's origin in world space. When used internally to the Box2D solver, this is relative to the center of mass.
separation (number) : The separation of the contact point, negative if penetrating
normalImpulse (number) : The impulse along the manifold normal vector
tangentImpulse (number) : The friction impulse
maxNormalImpulse (number) : The maximum normal impulse applied during sub-stepping
normalVelocity (number) : Relative normal velocity pre-solve. Used for hit events. If the normal impulse is zero then there was no hit. Negative means shapes are approaching.
id (number) : Uniquely identifies a contact point between two shapes
persisted (boolean) : Did this contact point exist the previous step?

b2Manifold

new b2Manifold()
Properties
points (Array<b2ManifoldPoint>) : The manifold points, up to two are possible in 2D
normal (b2Vec2) : The unit normal vector in world space, points from shape A to bodyB
pointCount (number) : The number of contacts points, will be 0, 1, or 2

b2TreeNode

new b2TreeNode()
Properties
aabb (b2AABB) : The node bounding box
categoryBits (number) : Category bits for collision filtering
parent (number) : The node parent index (allocated node)
next (number) : The node freelist next index (free node)
child1 (number) : Child 1 index (internal node)
child2 (number) : Child 2 index (internal node)
userData (number) : User data (leaf node)
height (number) : Node height
flags (number) : Node flags

Id

b2WorldId

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
new b2WorldId(index: any, revision: any)
Parameters
index (any = 0)
revision (any = 0)

b2WorldId

new b2WorldId(index: any, revision: any)
Parameters
index (any = 0)
revision (any = 0)

b2WorldId

new b2WorldId()
Properties
index1 (number) : Index value stored as unsigned 16-bit integer
revision (number) : Revision value stored as unsigned 16-bit integer

b2BodyId

new b2BodyId()
Properties
index1 (number) : Integer index value
world0 (number) : 16-bit world identifier
revision (number) : 16-bit revision number

b2ShapeId

new b2ShapeId()
Properties
index1 (number) : Integer index value
world0 (number) : 16-bit unsigned integer value
revision (number) : 16-bit unsigned integer value

b2JointId

new b2JointId()
Properties
index1 (number) : Integer index value
world0 (number) : 16-bit world identifier
revision (number) : 16-bit revision number

b2ChainId

new b2ChainId()
Properties
index1 (number) : Integer index value
world0 (number) : 16-bit unsigned integer value
revision (number) : 16-bit unsigned integer value

B2_IS_NULL

Tests if a contact ID represents a null/invalid contact by checking if its index1 property equals 0. In Box2D, an index1 value of 0 indicates a null contact ID.

B2_IS_NULL(id: Object): boolean
Parameters
id (Object) A contact ID object containing index1 property
Returns
boolean: Returns true if the contact ID is null (index1 === 0), false otherwise

B2_IS_NON_NULL

Tests whether a contact ID represents a valid contact by checking if its index1 property is not equal to 0. A zero value for index1 indicates a null contact ID.

B2_IS_NON_NULL(id: Object): boolean
Parameters
id (Object) A contact ID object containing an index1 property.
Returns
boolean: Returns true if the contact ID is non-null (index1 !== 0), false otherwise.

B2_ID_EQUALS

Performs a strict equality comparison between corresponding properties of two ID objects. Checks equality of index1, world0, and revision properties.

B2_ID_EQUALS(id1: Object, id2: Object): boolean
Parameters
id1 (Object) First ID object containing index1, world0, and revision properties.
id2 (Object) Second ID object containing index1, world0, and revision properties.
Returns
boolean: True if all corresponding properties between id1 and id2 are equal, false otherwise.

Helpers

b2Math

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Math

b2Math

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Math

b2Alloc

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Alloc(size: any, initCallback: any)
Parameters
size (any)
initCallback (any = null)

b2Alloc

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Alloc

b2Alloc

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Alloc

Allocate

Allocate

b2BitSet

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2BitSet

BitSet

BitSet

BlockArray

BlockArray

B2_HUGE

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_HUGE

B2_HUGE

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_HUGE

B2_HUGE

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_HUGE

B2_SHAPE_PAIR_KEY

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_SHAPE_PAIR_KEY

B2_SHAPE_PAIR_KEY

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_SHAPE_PAIR_KEY
Parameters
K1 (any)
K2 (any)

Broadphase

Broadphase

b2BroadPhase

The broad-phase is used for computing pairs and performing volume queries and ray casts. This broad-phase does not persist pairs. Instead, this reports potentially new pairs. It is up to the client to consume the new pairs and to track subsequent overlap.

new b2BroadPhase()

b2BroadPhase

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2BroadPhase

B2_NULL_INDEX

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_NULL_INDEX

B2_NULL_INDEX

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_NULL_INDEX

B2_NULL_INDEX

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_NULL_INDEX

B2_NULL_INDEX

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_NULL_INDEX

B2_NULL_INDEX

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_NULL_INDEX

B2_NULL_INDEX

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_NULL_INDEX

B2_NULL_INDEX

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_NULL_INDEX

ConstraintGraph

ConstraintGraph

Contact

Contact

ContactSolver

ContactSolver

loadPNGImage

IMAGE HELPERS

loadPNGImage(imageUrl: any)
Parameters
imageUrl (any)

getMousePosUV

UI HELPERS

getMousePosUV(canvas: any, ps: any)
Parameters
canvas (any)
ps (any)

B2_MAX_POLYGON_VERTICES

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_MAX_POLYGON_VERTICES

B2_MAX_POLYGON_VERTICES

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_MAX_POLYGON_VERTICES

B2_MAX_POLYGON_VERTICES

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_MAX_POLYGON_VERTICES

B2_MAX_POLYGON_VERTICES

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_MAX_POLYGON_VERTICES

B2_MAX_POLYGON_VERTICES

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_MAX_POLYGON_VERTICES

b2BodyType

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2BodyType

b2Validation

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Validation

IDPool

IDPool

b2Perimeter

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Perimeter

b2CreateBitSet

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2CreateBitSet

b2BodySimArray

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2BodySimArray

b2_overflowIndex

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2_overflowIndex

b2ContactFlags

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2ContactFlags

b2ContactConstraintPoint

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2ContactConstraintPoint

b2IsPowerOf2

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2IsPowerOf2(x: any)
Parameters
x (any)

b2DynamicTree_GetUserData

Get proxy user data

b2DynamicTree_GetUserData(tree: Object, proxyId: number): number
Parameters
tree (Object) The dynamic tree object
proxyId (number) The proxy ID
Returns
number: The proxy user data or 0 if the id is invalid

b2IdPool

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2IdPool

b2Island

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Island

b2PrepareMotorJoint

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2PrepareMotorJoint

b2PrepareMouseJoint

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2PrepareMouseJoint

b2DrawRevoluteJoint

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2DrawRevoluteJoint

b2Solve

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2Solve

b2SolverSet

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2SolverSet

b2StackAllocator

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2StackAllocator

b2StackAllocator

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
new b2StackAllocator()

b2PrepareWeldJoint

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2PrepareWeldJoint

b2DrawWheelJoint

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2DrawWheelJoint

b2_maxWorkers

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2_maxWorkers

Type: number

b2AddIsland

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2AddIsland

Island

Island

B2_PI

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_PI

Physics

Physics
Static Members
â–¸ new SpriteToBox(worldId, sprite, data)
â–¸ new SpriteToCircle(worldId, sprite, data)
â–¸ new CreateWorld(data)
â–¸ new CreateChain(data)
â–¸ new CreateCircle(data)
â–¸ new CreateCapsule(data)
â–¸ new CreateBoxPolygon(data)
â–¸ new CreateNGonPolygon(data)
â–¸ new CreatePolygon(data)
â–¸ new CreatePolygonFromEarcut(data)
â–¸ new CreatePolygonFromVertices(data)
â–¸ new CreatePhysicsEditorShape(data)
â–¸ new CreateRevoluteJoint(data)
â–¸ new CreateWeldJoint(data)
â–¸ new CreateDistanceJoint(data)
â–¸ new CreateWheelJoint(data)
â–¸ new CreatePrismaticJoint(data)
â–¸ new CreateMotorJoint(data)
â–¸ new CreateMouseJoint(data)

SetWorldScale

Set the scale of the Box2D World when converting from pixels to meters.

new SetWorldScale(scale: number)
Parameters
scale (number)

GetWorldScale

Get the current scale of the Box2D World, as used when converting from pixels to meters.

new GetWorldScale(): number
Returns
number:

mpx

Converts a single numerical value from meters to pixels.

mpx(meters: number): number
Parameters
meters (number)
Returns
number:

pxm

Converts a single numerical value from pixels to meters.

pxm(pixels: number): number
Parameters
pixels (number)
Returns
number:

pxmVec2

Converts the given x and y values from pixels to meters, stored in a new b2Vec2.

pxmVec2(x: number, y: number): b2Vec2
Parameters
x (number)
y (number)
Returns
b2Vec2:

RotFromRad

Convets the given value in radians to a b2Rot object, used for Box2D rotations.

new RotFromRad(radians: number): b2Rot
Parameters
radians (number)
Returns
b2Rot:

AddSpriteToWorld

Adds a Sprite Game Object to the given World, attaching it to the given Body.

new AddSpriteToWorld(worldId: number, sprite: Sprite, body: b2Body)
Parameters
worldId (number)
sprite (Sprite)
body (b2Body)

RemoveSpriteFromWorld

Removes a Sprite Game Object from the given World, optionally destroying the Body it was attached to.

new RemoveSpriteFromWorld(worldId: number, sprite: Sprite, destroyBody: boolean)
Parameters
worldId (number)
sprite (Sprite)
destroyBody (boolean = false)

ClearWorldSprites

Clears all Sprite to Body pairs. Neither the Sprites nor the Bodies are destroyed. The bodies remain in the world.

new ClearWorldSprites(worldId: number)
Parameters
worldId (number)

GetBodyFromSprite

Returns the Body attached to the given Sprite in the given World. Or null if no such pair exists.

new GetBodyFromSprite(worldId: number, sprite: Sprite): (Sprite | null)
Parameters
worldId (number)
sprite (Sprite)
Returns
(Sprite | null): Either the sprite, or null .

UpdateWorldSprites

Runs through all World-Sprite pairs and updates the Sprite positions and rotations to match the Body.

new UpdateWorldSprites(worldId: number)
Parameters
worldId (number)

BodyToSprite

Converts a Box2D Body's position and rotation to a Sprite's position and rotation.

This is called automatically by UpdateWorldSprites.

new BodyToSprite(body: b2Body, sprite: Sprite)
Parameters
body (b2Body)
sprite (Sprite)

Sprite

Sprite

Type: Object

Properties
x (number) : The x position of the sprite.
y (number) : The y position of the sprite.
width (number) : The width of the sprite.
height (number) : The height of the sprite.
rotation (number) : The rotation of the sprite in radians.
scaleX (number?) : Optional horizontal scale of the sprite.
scaleY (number?) : Optional vertical scale of the sprite.
scale (b2Vec2?) : Optional scale vector of the sprite.

WorldConfig

WorldConfig

Type: Object

Properties
worldDef (b2WorldDef?) : World definition

WorldStepConfig

WorldStepConfig

Type: Object

Properties
worldId (b2WorldId) : The world ID value
deltaTime (number) : How long has it been since the last call (e.g. the value passed to a RAF update)
fixedTimeStep (number?) : Duration of the fixed timestep for the Physics simulation
subStepCount (number?) : Number of sub-steps performed per world step

WorldStep

Steps a physics world to match fixedTimeStep. Returns the average time spent in the step function.

new WorldStep(data: WorldConfig): number
Parameters
data (WorldConfig) Configuration for the world.
Returns
number: totalTime - Time spent processing the step function, in seconds.

ChainConfig

ChainConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world.
groundId (b2BodyId) : ID for the static ground to attach the chain ends to.
type (number?) : Type of the body (static, dynamic, kinematic).
firstLinkPosition (b2Vec2) : Position of the first link.
lastLinkPosition (b2Vec2) : Position of the last link.
chainLinks (number) : Number of links in the chain.
linkLength (number) : Length of each link
density (number?) : Density of the links.
friction (number?) : Friction of the links.
color (any?) : Custom color for the links.
radius (number?) : Radius for the circle 'caps' on each capsule link.
fixEnds (boolean) : Should the ends of the chain be fixed to the groundId object?

BodyCapsule

BodyCapsule

Type: Object

Properties
bodyId (b2BodyId) : ID for the body to attach the capsule to.
shapeId (b2ShapeId) : ID for the shape to attach the capsule to.

CircleConfig

CircleConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world in which to create the circle.
bodyDef (b2BodyDef?) : Body definition for the circle.
type (number?) : Type of the body (static, dynamic, kinematic).
position (b2Vec2?) : Position of the circle's center.
bodyId (b2BodyId?) : Existing body ID if adding as a fixture.
shapeDef (b2ShapeDef?) : Shape definition for the circle.
groupIndex (number?) : Collision filtering, group index for the circle.
categoryBits (number?) : Collision filtering, what 'category' is this cirle in?
maskBits (number?) : Collision filtering, what 'categories' will this circle collide with?
density (number?) : Density of the circle.
friction (number?) : Friction of the circle.
restitution (number?) : Restitution of the circle.
color (any?) : Custom color for the circle.
radius (number?) : Radius of the circle.
preSolve (boolean?) : Enable presolve callback for the circle.
isSensor (boolean?) : A sensor shape generates overlap events but never generates a collision response
offset (b2Vec2?) : Offset of the circle's center when adding as a fixture.

CapsuleConfig

CapsuleConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world in which to create the capsule.
bodyDef (b2BodyDef?) : Body definition for the capsule.
type (number?) : Type of the body (static, dynamic, kinematic).
position (b2Vec2?) : Position of the capsule's center.
bodyId (b2BodyId?) : Existing body ID if adding as a fixture.
shapeDef (b2ShapeDef?) : Shape definition for the capsule.
density (number?) : Density of the capsule.
friction (number?) : Friction of the capsule.
groupIndex (number?) : Collision group index for the capsule.
categoryBits (number?) : Collision filtering, what 'category' is this in?
maskBits (number?) : Collision filtering, what 'categories' will this collide with?
color (any?) : Custom color for the capsule.
center1 (b2Vec2?) : Center of the first circle of the capsule. Optional if 'height' is set.
center2 (b2Vec2?) : Center of the second circle of the capsule. Optional if 'height' is set.
radius (number?) : Radius of the capsule's circles. Optional if 'width' is set.
fixedRotation (boolean?) : Prevent rotation if set to true.
linearDamping (number?) : Linear damping of velocity.
width (number?) : The overall width of the capsule. If set replaces radius.
height (number?) : The overall height of the capsule, including the start and end caps. If set replaces center1 and center2.

BoxPolygonConfig

BoxPolygonConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world in which to create the box.
bodyDef (b2BodyDef?) : Body definition for the box.
type (number?) : Type of the body (static, dynamic, kinematic).
position (b2Vec2?) : Position of the box's center.
fixedRotation (boolean?) : Prevent box from rotating?
linearDamping (number?) : Damping for linear velocity.
angularDamping (number?) : Damping for angular velocity.
bodyId (b2BodyId?) : Existing body ID if adding as a fixture.
shapeDef (b2ShapeDef?) : Shape definition for the box.
userData (any?) : The user data to associate with the body.
groupIndex (number?) : Collision group index for the box.
categoryBits (number?) : Collision filtering, what 'category' is this in?
maskBits (number?) : Collision filtering, what 'categories' will this collide with?
density (number?) : Density of the box.
friction (number?) : Friction of the box.
restitution (number?) : Restitution of the box.
color (any?) : Custom color for the box.
preSolve (boolean?) : Enable presolve callback for the circle.
size ((b2Vec2 | number)) : Size of the box (either a b2Vec2 or a single number for square).

NGonPolygonConfig

NGonPolygonConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world in which to create the n-gon.
bodyDef (b2BodyDef?) : Body definition for the n-gon.
type (number?) : Type of the body (static, dynamic, kinematic).
position (b2Vec2?) : Position of the n-gon's center.
bodyId (b2BodyId?) : Existing body ID if adding as a fixture.
shapeDef (b2ShapeDef?) : Shape definition for the n-gon.
groupIndex (number?) : Collision group index for the n-gon.
density (number?) : Density of the n-gon.
friction (number?) : Friction of the n-gon.
color (any?) : Custom color for the n-gon.
radius (number) : Radius of the n-gon.
sides (number) : Number of sides for the n-gon.

PolygonConfig

PolygonConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world in which to create the polygon.
bodyDef (b2BodyDef?) : Body definition for the polygon.
type (number?) : Type of the body (static, dynamic, kinematic).
position (b2Vec2?) : Position of the polygon's center.
bodyId (b2BodyId?) : Existing body ID if adding as a fixture.
shapeDef (b2ShapeDef?) : Shape definition for the polygon.
groupIndex (number?) : Collision group index for the polygon.
density (number?) : Density of the polygon.
friction (number?) : Friction of the polygon.
color (any?) : Custom color for the polygon.
vertices (Array<b2Vec2>) : List of vertices for the polygon.

PolygonVertexConfig

PolygonVertexConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world in which to create the polygon.
bodyDef (b2BodyDef?) : Body definition for the polygon.
type (number?) : Type of the body (static, dynamic, kinematic).
position (b2Vec2?) : Position of the polygon's center.
bodyId (b2BodyId?) : Existing body ID if adding as a fixture.
shapeDef (b2ShapeDef?) : Shape definition for the polygon.
groupIndex (number?) : Collision group index for the polygon.
density (number?) : Density of the polygon.
friction (number?) : Friction of the polygon.
restitution (number?) : Restitution of the polygon.
color (any?) : Custom color for the polygon.
indices (Array<number>) : List of indices to the vertices for the polygon.
vertices (Array<number>) : List of vertices for the polygon in number pairs [x0,y0, x1,y1, ... xN,yN].
vertexOffset (b2Vec2) : Offset to recenter the vertices if they are not zero based.
vertexScale (b2Vec2) : Scale for the vertices, defaults to 1, 1.
url (string?) : URL location of the XML data file, if we're using one.
key (string?) : Name 'key' to find the correct data in the XML.

RevoluteJointConfig

RevoluteJointConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world in which the bodies and joint exist.
jointDef (b2RevoluteJointDef?) : A pre-existing b2RevoluteJointDef.
bodyIdA (b2BodyId) : The first body to connect with this joint.
bodyIdB (b2BodyId) : The second body to connect with this joint.
anchorA (b2Vec2?) : Local position of the anchor point on the first body.
anchorB (b2Vec2?) : Local position of the anchor point on the second body.
lowerAngle (number?) : Lower limit of the joint's angle.
upperAngle (number?) : Upper limit of the joint's angle.
enableLimit (boolean?) : Whether to enable angle limits.
enableMotor (boolean?) : Whether to enable the joint's motor.
motorSpeed (number?) : The desired motor speed.
maxMotorTorque (number?) : The maximum torque the motor can apply.
enableSpring (boolean?) : Whether to enable the joint's spring.
hertz (number?) : The frequency of the joint's spring.
dampingRatio (number?) : The damping ratio of the joint's spring.
collideConnected (boolean?) : Whether the connected bodies should collide.
drawSize (number?) : The size to use when drawing the joint.

WeldJointConfig

WeldJointConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world in which the bodies and joint exist.
jointDef (b2WeldJointDef?) : A pre-existing b2WeldJointDef.
bodyIdA (b2BodyId) : The first body to weld with this joint.
bodyIdB (b2BodyId) : The second body to weld with this joint.
anchorA (b2Vec2?) : Local position of the anchor point on the first body.
anchorB (b2Vec2?) : Local position of the anchor point on the second body.
hertz (number?) : The frequency at which the weld joint is enforced.
dampingRatio (number?) : The angular damping ratio when the weld joint is springing back into alignment.
referenceAngle (number?) : Reference angle for the weld joint at rest.
collideConnected (boolean?) : Whether the connected bodies should collide.

DistanceJointConfig

DistanceJointConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world in which the bodies and joint exist.
jointDef (b2DistanceJointDef?) : A pre-existing b2DistanceJointDef.
bodyIdA (b2BodyId) : The first body to connect with this joint.
bodyIdB (b2BodyId) : The second body to connect with this joint.
anchorA (b2Vec2?) : Local position of the anchor point on the first body.
anchorB (b2Vec2?) : Local position of the anchor point on the second body.
length (number?) : The natural length of the joint.
minLength (number?) : The minimum allowed length of the joint.
maxLength (number?) : The maximum allowed length of the joint.
enableSpring (boolean?) : Whether to enable the joint's spring.
hertz (number?) : The frequency of the joint's spring.
dampingRatio (number?) : The damping ratio of the joint's spring.
enableLimit (boolean?) : Whether to enable length limits.
collideConnected (boolean?) : Whether the connected bodies should collide.

WheelJointConfig

WheelJointConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world in which the bodies and joint exist.
jointDef (b2WheelJointDef?) : A pre-existing b2WheelJointDef.
bodyIdA (b2BodyId) : The first body to connect with this joint.
bodyIdB (b2BodyId) : The second body to connect with this joint.
anchorA (b2Vec2?) : Local position of the anchor point on the first body.
anchorB (b2Vec2?) : Local position of the anchor point on the second body.
enableSpring (boolean?) : Whether to enable the joint's spring.
axis (b2Vec2?) : The local axis for the joint movement on body A.
hertz (number?) : The frequency of the joint's spring.
dampingRatio (number?) : The damping ratio of the joint's spring.
enableLimit (boolean?) : Whether to enable translation limits.
lowerTranslation (number?) : The lower translation limit.
upperTranslation (number?) : The upper translation limit.
enableMotor (boolean?) : Whether to enable the joint's motor.
maxMotorTorque (number?) : The maximum torque the motor can apply.
motorSpeed (number?) : The desired motor speed.
collideConnected (boolean?) : Whether the connected bodies should collide.

PrismaticJointConfig

PrismaticJointConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world in which the bodies and joint exist.
jointDef (b2PrismaticJointDef?) : A pre-existing b2PrismaticJointDef.
bodyIdA (b2BodyId) : The first body to connect with this joint.
bodyIdB (b2BodyId) : The second body to connect with this joint.
anchorA (b2Vec2?) : Local position of the anchor point on the first body.
anchorB (b2Vec2?) : Local position of the anchor point on the second body.
axis (b2Vec2?) : The local axis for the joint movement on body A.
referenceAngle (number?) : The reference angle between the bodies.
enableSpring (boolean?) : Whether to enable the joint's spring.
hertz (number?) : The frequency of the joint's spring.
dampingRatio (number?) : The damping ratio of the joint's spring.
enableLimit (boolean?) : Whether to enable translation limits.
lowerTranslation (number?) : The lower translation limit.
upperTranslation (number?) : The upper translation limit.
enableMotor (boolean?) : Whether to enable the joint's motor.
maxMotorForce (number?) : The maximum force the motor can apply.
motorSpeed (number?) : The desired motor speed.
collideConnected (boolean?) : Whether the connected bodies should collide.

MotorJointConfig

MotorJointConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world in which the bodies and joint exist.
jointDef (b2MotorJointDef?) : A pre-existing b2MotorJointDef.
bodyIdA (b2BodyId) : The first body to connect with this joint.
bodyIdB (b2BodyId) : The second body to connect with this joint.
linearOffset (b2Vec2?) : The desired linear offset in frame A.
maxForce (number?) : The maximum force that can be applied to reach the target offsets.
angularOffset (number?) : The desired angular offset.
maxTorque (number?) : The maximum torque that can be applied to reach the target angular offset.
correctionFactor (number?) : Position correction factor in the range [0,1].
collideConnected (boolean?) : Whether the connected bodies should collide.

MouseJointConfig

MouseJointConfig

Type: Object

Properties
worldId (b2WorldId) : ID for the world in which the bodies and joint exist.
jointDef (b2MouseJointDef?) : A pre-existing b2MouseJointDef.
bodyIdA (b2BodyId) : The first (usually static) body to connect with this joint.
bodyIdB (b2BodyId) : The second (usually dynamic) body to connect with this joint.
target (b2Vec2?) : The initial world target point.
hertz (number?) : The response frequency.
dampingRatio (number?) : The damping ratio.
maxForce (number?) : The maximum force that can be exerted to reach the target point.
collideConnected (boolean?) : Whether the connected bodies should collide. e.g. worldId:worldId, bodyIdA:mouseCircle.bodyId, bodyIdB:mouseBox.bodyId, target:new b2Vec2(0, 0), hertz:30.0, dampingRatio:0.999, maxForce:35000

Ragdoll

Ragdoll

bitset_h

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
bitset_h

Solver

Solver

b2IntegratePositionsTask

function b2PrepareJointsTask(startIndex, endIndex, context) { const joints = context.joints;

for (let i = startIndex; i < endIndex; ++i) { const joint = joints[i]; joint_h.b2PrepareJoint(joint, context); } }

b2IntegratePositionsTask(startIndex: any, endIndex: any, context: any)
Parameters
startIndex (any)
endIndex (any)
context (any)

SolverSet

SolverSet

StackAllocator

StackAllocator

b2CreateSet

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
b2CreateSet()

Table

Table

B2_DEFAULT_MASK_BITS

This file includes code that is:

  • Copyright 2023 Erin Catto, released under the MIT license.
  • Copyright 2024 Phaser Studio Inc, released under the MIT license.
B2_DEFAULT_MASK_BITS