Class Body

A rigid body. Has got a center of mass, position, velocity and a number of shapes that are used for collisions.

Example

// Create a typical dynamic body
var body = new Body({
mass: 1, // non-zero mass will set type to Body.DYNAMIC
position: [0, 5],
angle: 0,
velocity: [0, 0],
angularVelocity: 0
});

// Add a circular shape to the body
var circleShape = new Circle({ radius: 0.5 });
body.addShape(circleShape);

// Add the body to the world
world.addBody(body);

Example

// Create a static plane body
var planeBody = new Body({
mass: 0, // zero mass will set type to Body.STATIC
position: [0, 0]
});
var planeShape = new Plane();
planeBody.addShape(planeShape);
world.addBody(planeBody);

Example

// Create a moving kinematic box body
var platformBody = new Body({
type: Body.KINEMATIC,
position: [0, 3],
velocity: [1, 0]
});
var boxShape = new Box({ width: 2, height: 0.5 });
platformBody.addShape(boxShape);
world.addBody(platformBody);

Hierarchy

Constructors

Properties

aabb: AABB

Bounding box of this body. Update with updateAABB.

aabbNeedsUpdate: boolean

Indicates if the AABB needs update. Update it with "Body.updateAABB".

Example

// Force update the AABB
body.aabbNeedsUpdate = true;
body.updateAABB();
console.log(body.aabbNeedsUpdate); // false
allowSleep: boolean

If true, the body will automatically fall to sleep. Note that you need to enable sleeping in the World before anything will happen.

Default

true
angle: number

The angle of the body, in radians.

Example

// The angle property is not normalized to the interval 0 to 2*pi, it can be any value.
// If you need a value between 0 and 2*pi, use the following function to normalize it.
function normalizeAngle(angle){
angle = angle % (2*Math.PI);
if(angle < 0){
angle += (2*Math.PI);
}
return angle;
}
angularDamping: number

The angular force acting on the body. Should be a value between 0 and 1.

Default

0.1
angularForce: number

The angular force acting on the body. See force.

angularVelocity: number

The angular velocity of the body, in radians per second.

boundingRadius: number

Bounding circle radius. Update with updateBoundingRadius.

ccdIterations: number

The number of iterations that should be used when searching for the time of impact during CCD. A larger number will assure that there's a small penetration on CCD collision, but a small number will give more performance.

Default

10
ccdSpeedThreshold: number

If the body speed exceeds this threshold, CCD (continuous collision detection) will be enabled. Set it to a negative number to disable CCD completely for this body.

Default

-1
collisionResponse: boolean

Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this body will move through other bodies, but it will still trigger contact events, etc.

damping: number

The linear damping acting on the body in the velocity direction. Should be a value between 0 and 1.

Default

0.1
fixedRotation: boolean

Set to true if you want to fix the rotation of the body.

Example

// Fix rotation during runtime
body.fixedRotation = true;
body.updateMassProperties();
fixedX: boolean

Set to true if you want to fix the body movement along the X axis. The body will still be able to move along Y.

Example

// Fix X movement on body creation
var body = new Body({ mass: 1, fixedX: true });

Example

// Fix X movement during runtime
body.fixedX = true;
body.updateMassProperties();
fixedY: boolean

Set to true if you want to fix the body movement along the Y axis. The body will still be able to move along X. See .fixedX

force: Vec2

The force acting on the body. Since the body force (and angularForce) will be zeroed after each step, so you need to set the force before each step.

Example

// This produces a forcefield of 1 Newton in the positive x direction.
for(var i=0; i<numSteps; i++){
body.force[0] = 1;
world.step(1/60);
}

Example

// This will apply a rotational force on the body
for(var i=0; i<numSteps; i++){
body.angularForce = -3;
world.step(1/60);
}
gravityScale: number

Gravity scaling factor. If you want the body to ignore gravity, set this to zero. If you want to reverse gravity, set it to -1.

Default

1
id: number

The body identifier

idleTime: number

How long the body has been sleeping.

index: number

Index of the body in the World .bodies array. Is set to -1 if the body isn't added to a World.

inertia: number

The inertia of the body around the Z axis.

interpolatedAngle: number

The interpolated angle of the body. Use this for rendering.

interpolatedPosition: Vec2

The interpolated position of the body. Use this for rendering.

invInertia: number

The inverse inertia of the body.

invInertiaSolve: number
invMass: number

The inverse mass of the body.

invMassSolve: number
mass: number

The mass of the body. If you change this number, you should call updateMassProperties.

Example

body.mass = 1;
body.updateMassProperties();
position: Vec2

The position of the body in the world. Don't use this for rendering, instead use .interpolatedPosition

previousAngle: number

The previous angle of the body.

previousPosition: Vec2

The previous position of the body.

shapes: Shape[]

The shapes of the body.

sleepSpeedLimit: number

If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.

Default

0.2
sleepState: 0 | 2 | 1

One of AWAKE, SLEEPY and SLEEPING.

The body is initially Body.AWAKE. If its velocity norm is below .sleepSpeedLimit, the sleepState will become Body.SLEEPY. If the body continues to be Body.SLEEPY for .sleepTimeLimit seconds, it will fall asleep (Body.SLEEPY).

Default

Body.AWAKE
sleepTimeLimit: number

If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.

Default

1
timeLastSleepy: number

The last time when the body went to SLEEPY state.

type: 2 | 1 | 4

The type of motion this body has. Should be one of: STATIC, DYNAMIC and KINEMATIC.

  • Static bodies do not move, and they do not respond to forces or collision.
  • Dynamic bodies body can move and respond to collisions and forces.
  • Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force.

Example

// Bodies are static by default. Static bodies will never move.
var body = new Body();
console.log(body.type == Body.STATIC); // true

Example

// By setting the mass of a body to a nonzero number, the body
// will become dynamic and will move and interact with other bodies.
var dynamicBody = new Body({
mass : 1
});
console.log(dynamicBody.type == Body.DYNAMIC); // true

Example

// Kinematic bodies will only move if you change their velocity.
var kinematicBody = new Body({
type: Body.KINEMATIC // Type can be set via the options object.
});
velocity: Vec2

The current velocity of the body.

vlambda: Vec2

Constraint velocity that was added to the body during the last step.

wantsToSleep: boolean

Whether the body wants to sleep

wlambda: number

Angular constraint velocity that was added to the body during last step.

world: null | World = null

The world that this body is added to (read only). This property is set to NULL if the body is not added to any world.

AWAKE: 0 = ...

Awake sleep state.

DYNAMIC: 1 = ...

Dynamic body.

KINEMATIC: 4 = ...

Kinematic body.

SLEEPING: 2 = ...

Sleeping sleep state.

SLEEPY: 1 = ...

Sleepy sleep state.

STATIC: 2 = ...

Static body.

_idCounter: number = 0

Id counter for Body instances

Methods

  • Returns void

  • Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and angle relative to the body center of mass. Will automatically update the mass properties and bounding radius.

    Parameters

    • shape: Shape
    • Optional offset: Vec2

      Local body offset of the shape.

    • Optional angle: number

      Local body angle.

    Returns void

    Example

    var body = new Body(),
    shape = new Circle({ radius: 1 });

    // Add the shape to the body, positioned in the center
    body.addShape(shape);

    // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis.
    body.addShape(shape,[1,0]);

    // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW.
    body.addShape(shape,[0,1],Math.PI/2);
  • Moves the shape offsets so their center of mass becomes the body center of mass.

    Returns void

    Example

    var body = new Body({ position: [0, 0] });
    var shape = new Circle({ radius: 1 });
    body.addShape(shape, [1, 0], 0);
    body.adjustCenterOfMass();
    console.log(body.position); // [1, 0]
    console.log(shape.position); // [0, 0]
  • Apply damping, see this for details.

    Parameters

    • dt: number

      Current time step

    Returns void

  • Apply force to a point relative to the center of mass of the body. This could for example be a point on the Body surface. Applying force this way will add to Body.force and Body.angularForce.

    Parameters

    • force: Vec2

      The force vector to add, oriented in world space.

    • Optional relativePoint: Vec2

      A point relative to the body in world space. If not given, it is set to zero and all of the force will be exerted on the center of mass.

    Returns void

    Example

    var body = new Body({ mass: 1 });
    var relativePoint = [1, 0]; // Will apply the force at [body.position[0] + 1, body.position[1]]
    var force = [0, 1]; // up
    body.applyForce(force, relativePoint);
    console.log(body.force); // [0, 1]
    console.log(body.angularForce); // 1
  • Apply force to a point relative to the center of mass of the body. This could for example be a point on the Body surface. Applying force this way will add to Body.force and Body.angularForce.

    Parameters

    • localForce: Vec2

      The force vector to add, oriented in local body space.

    • Optional localPoint: Vec2

      A point relative to the body in local body space. If not given, it is set to zero and all of the force will be exerted on the center of mass.

    Returns void

    Example

    var body = new Body({ mass: 1 });
    var localPoint = [1, 0]; // x=1 locally in the body
    var localForce = [0, 1]; // up, locally in the body
    body.applyForceLocal(localForce, localPoint);
    console.log(body.force); // [0, 1]
    console.log(body.angularForce); // 1
  • Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.

    Parameters

    • impulseVector: Vec2

      The impulse vector to add, oriented in world space.

    • Optional relativePoint: Vec2

      A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass.

    Returns void

    Example

    var body = new Body({ mass: 1 });
    var relativePoint = [0, 0]; // center of the body
    var impulseVector = [0, 1]; // world up
    body.applyImpulse(impulseVector, relativePoint);
  • Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.

    Parameters

    • localImpulse: Vec2

      The impulse vector to add, oriented in local body space.

    • Optional localPoint: Vec2

      A point relative to the body in local body space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass.

    Returns void

    Example

    var body = new Body({ mass: 1 });
    var localPoint = [1, 0]; // x=1, locally in the body
    var localImpulse = [0, 1]; // up, locally in the body
    body.applyImpulseLocal(localImpulse, localPoint);
    console.log(body.velocity); // [1, 0]
    console.log(body.angularVelocity); // 1
  • Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points.

    Parameters

    • path: Vec2[]

      An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes.

    • options: {
          optimalDecomp?: boolean;
          removeCollinearPoints?: number | boolean;
          skipSimpleCheck?: boolean;
      } = {}
      • Optional optimalDecomp?: boolean
      • Optional removeCollinearPoints?: number | boolean
      • Optional skipSimpleCheck?: boolean

    Returns boolean

    True on success, else false.

    Example

    var body = new Body();
    var path = [
    [-1, 1],
    [-1, 0],
    [1, 0],
    [1, 1],
    [0.5, 0.5]
    ];
    body.fromPolygon(path);
    console.log(body.shapes); // [Convex, Convex, ...]
  • Get the AABB from the body. The AABB is updated if necessary.

    Returns AABB

    The AABB instance from the body.

  • Get the total area of all shapes in the body

    Returns number

    total area of all shapes in the body

  • Get velocity of a point in the body.

    Parameters

    • result: Vec2

      A vector to store the result in

    • relativePoint: Vec2

      A world oriented vector, indicating the position of the point to get the velocity from

    Returns Vec2

    The result vector

    Example

    var body = new Body({
    mass: 1,
    velocity: [1, 0],
    angularVelocity: 1
    });
    var result = [];
    var point = [1, 0];
    body.getVelocityAtPoint(result, point);
    console.log(result); // [1, 1]
  • Check if an event listener is added

    Type Parameters

    Parameters

    • type: E
    • Optional listener: ((e) => void)

    Returns boolean

  • Move the body forward in time given its current velocity.

    Parameters

    • dt: number

    Returns void

  • Parameters

    • dt: number

    Returns boolean

  • Remove an event listener

    Type Parameters

    Parameters

    • type: E
    • listener: ((e) => void)

    Returns EventEmitter<BodyEventMap>

    The self object, for chainability.

    Example

    emitter.on('myEvent', handler); // Add handler
    emitter.off('myEvent', handler); // Remove handler
  • Add an event listener

    Type Parameters

    Parameters

    • type: E
    • listener: ((e) => void)

    Returns EventEmitter<BodyEventMap>

    The self object, for chainability.

    Example

    emitter.on('myEvent', function(evt){
    console.log('myEvt was triggered!');
    });
  • Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken.

    Parameters

    Returns boolean

    if the body overlaps the given body

  • Remove a shape.

    Parameters

    Returns boolean

    True if the shape was found and removed, else false.

  • Returns void

  • Set the total density of the body

    Parameters

    • density: number

    Returns void

  • Sets the force on the body to zero.

    Returns void

  • Force body sleep

    Returns void

  • Called every timestep to update internal sleep timer and change sleep state if needed.

    Parameters

    • time: number

      The world time in seconds

    • dontSleep: boolean
    • dt: number

    Returns void

  • Transform a world point to local body frame.

    Parameters

    • out: Vec2

      The point to store the result in

    • worldPoint: Vec2

      The input world point

    Returns void

  • Transform a local point to world frame.

    Parameters

    • out: Vec2

      The point to store the result in

    • localPoint: Vec2

      The input local point

    Returns void

  • Updates the AABB of the Body, and set .aabbNeedsUpdate = false.

    Returns void

  • Update the bounding radius of the body (this.boundingRadius). Should be done if any of the shape dimensions or positions are changed.

    Returns void

  • Updates .inertia, .invMass, .invInertia for this Body. Should be called when changing the structure or mass of the Body.

    Returns void

    Example

    body.mass += 1;
    body.updateMassProperties();
  • Returns void

  • Transform a world vector to local body frame.

    Parameters

    • out: Vec2

      The vector to store the result in

    • worldVector: Vec2

      The input world vector

    Returns void

  • Transform a local vector to world frame.

    Parameters

    • out: Vec2

      The vector to store the result in

    • localVector: Vec2

      The input local vector

    Returns void

  • Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. Sets the sleepState to AWAKE and emits the wakeUp event if the body wasn't awake before.

    Returns void