API Docs for: 0.7.1
Show:

Body Class

Extends EventEmitter

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

Constructor

Body

(
  • [options]
)

Parameters:

  • [options] Object optional
    • [force] Array optional
    • [position] Array optional
    • [velocity] Array optional
    • [allowSleep] Boolean optional
    • [collisionResponse] Boolean optional
    • [angle=0] Number optional
    • [angularForce=0] Number optional
    • [angularVelocity=0] Number optional
    • [ccdIterations=10] Number optional
    • [ccdSpeedThreshold=-1] Number optional
    • [fixedRotation=false] Number optional
    • [gravityScale] Number optional
    • [id] Number optional
    • [mass=0] Number optional

      A number >= 0. If zero, the .type will be set to Body.STATIC.

    • [sleepSpeedLimit] Number optional
    • [sleepTimeLimit] Number optional

Example:

// Create a typical dynamic body
        var body = new Body({
            mass: 1,
            position: [0, 0],
            angle: 0,
            velocity: [0, 0],
            angularVelocity: 0
        });
        
        // Add a circular shape to the body
        body.addShape(new Circle({ radius: 1 }));
        
        // Add the body to the world
        world.addBody(body);
        

Methods

addShape

(
  • shape
  • [offset]
  • [angle]
)

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
  • [offset] Array optional

    Local body offset of the shape.

  • [angle] Number optional

    Local body angle.

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);

adjustCenterOfMass

()

Moves the shape offsets so their center of mass becomes the body center of mass.

applyDamping

(
  • dt
)

Apply damping, see this for details.

Parameters:

  • dt Number

    Current time step

applyForce

(
  • force
  • [relativePoint]
)

Apply force to a point relative to the center of mass of the body. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. If relativePoint is zero, the force will be applied directly on the center of mass, and the torque produced will be zero.

Parameters:

  • force Array

    The force to add.

  • [relativePoint] Array optional

    A world point to apply the force on.

applyForceLocal

(
  • localForce
  • [localPoint]
)

Apply force to a body-local point.

Parameters:

  • localForce Array

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

  • [localPoint] Array optional

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

applyImpulse

(
  • impulse
  • [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:

  • impulse Array

    The impulse vector to add, oriented in world space.

  • [relativePoint] Array optional

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

applyImpulseLocal

(
  • impulse
  • [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:

  • impulse Array

    The impulse vector to add, oriented in world space.

  • [relativePoint] Array optional

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

emit

(
  • event
)
EventEmitter

Emit an event.

Parameters:

  • event Object
    • type String

Returns:

EventEmitter:

The self object, for chainability.

fromPolygon

(
  • path
  • [options]
)
Boolean

Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points.

Parameters:

  • path Array

    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] Object optional
    • [optimalDecomp=false] Boolean optional

      Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.

    • [skipSimpleCheck=false] Boolean optional

      Set to true if you already know that the path is not intersecting itself.

    • [removeCollinearPoints=false] Boolean | Number optional

      Set to a number (angle threshold value) to remove collinear points, or false to keep all points.

Returns:

Boolean:

True on success, else false.

getAABB

() AABB

Get the AABB from the body. The AABB is updated if necessary.

Returns:

AABB:

The AABB instance (this.aabb)

getArea

() Number

Get the total area of all shapes in the body

Returns:

Number:

getVelocityAtPoint

(
  • result
  • relativePoint
)
Array

Get velocity of a point in the body.

Parameters:

  • result Array

    A vector to store the result in

  • relativePoint Array

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

Returns:

Array:

The result vector

has

(
  • type
  • listener
)
Boolean

Check if an event listener is added

Parameters:

  • type String
  • listener Function

Returns:

Boolean:

integrate

(
  • dt
)

Move the body forward in time given its current velocity.

Parameters:

  • dt Number

off

(
  • type
  • listener
)
EventEmitter

Remove an event listener

Parameters:

  • type String
  • listener Function

Returns:

EventEmitter:

The self object, for chainability.

on

(
  • type
  • listener
)
EventEmitter

Add an event listener

Parameters:

  • type String
  • listener Function

Returns:

EventEmitter:

The self object, for chainability.

overlaps

(
  • body
)
Boolean

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:

removeShape

(
  • shape
)
Boolean

Remove a shape

Parameters:

Returns:

Boolean:

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

setDensity

(
  • density
)

Set the total density of the body

Parameters:

  • density Number

setZeroForce

()

Sets the force on the body to zero.

sleep

()

Force body sleep

sleepTick

(
  • time
  • dontSleep
  • dt
)

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

toLocalFrame

(
  • out
  • worldPoint
)

Transform a world point to local body frame.

Parameters:

  • out Array

    The vector to store the result in

  • worldPoint Array

    The input world point

toWorldFrame

(
  • out
  • localPoint
)

Transform a local point to world frame.

Parameters:

  • out Array

    The vector to store the result in

  • localPoint Array

    The input local point

updateAABB

()

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

updateBoundingRadius

()

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

updateMassProperties

()

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

Example:

body.mass += 1;
body.updateMassProperties();

updateSolveMassProperties

() private

vectorToLocalFrame

(
  • out
  • worldVector
)

Transform a world point to local body frame.

Parameters:

  • out Array

    The vector to store the result in

  • worldVector Array

    The input world vector

vectorToWorldFrame

(
  • out
  • localVector
)

Transform a local point to world frame.

Parameters:

  • out Array

    The vector to store the result in

  • localVector Array

    The input local vector

wakeUp

()

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 Body.AWAKE and emits the wakeUp event if the body wasn't awake before.

Properties

aabb

AABB

Bounding box of this body.

aabbNeedsUpdate

Boolean

Indicates if the AABB needs update. Update it with .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.

AWAKE

Number static

boundingRadius

Number

Bounding circle radius.

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

DYNAMIC

Number static

Dynamic body.

fixedRotation

Boolean

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

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.

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.

force

Array

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);
                    }
                    
// 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 identifyer

idleTime

Number

How long the body has been sleeping.

inertia

Number

The inertia of the body around the Z axis.

interpolatedAngle

Number

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

interpolatedPosition

Array

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

invInertia

Number

The inverse inertia of the body.

invMass

Number

The inverse mass of the body.

KINEMATIC

Number static

Kinematic body.

mass

Number

The mass of the body.

massMultiplier

Array private

position

Array

The position of the body

previousAngle

Number

The previous angle of the body.

previousPosition

Array

The previous position of the body.

shapes

Array

The shapes of the body.

SLEEPING

Number static

sleepSpeedLimit

Number

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

Default: 0.2

sleepState

Number

One of Body.AWAKE, Body.SLEEPY and Body.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

SLEEPY

Number static

STATIC

Number static

Static body.

timeLastSleepy

Number private

The last time when the body went to SLEEPY state.

type

Number

The type of motion this body has. Should be one of: Body.STATIC, Body.DYNAMIC and Body.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
                    
// 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
                    
// 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

Array

The current velocity of the body.

vlambda

Array

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

wlambda

Array

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

world

World

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

Events

sleep

sleepy

wakeup