Show:
API

Matter.Body

Defined in: src/body/Body.js:1

The Matter.Body module contains methods for creating and manipulating rigid bodies. For creating bodies with common configurations such as rectangles, circles and other polygons see the module Matter.Bodies.

See the included usage examples.

Methods

Matter.Body._initProperties

(body, [options])
private

Initialises body properties.

Parameters

Matter.Body._totalProperties

(body)
Object private

Returns the sums of the properties of all compound parts of the parent body.

Parameters

Returns

Matter.Body.applyForce

(body, position, force)

Applies the force to the body from the force origin position in world-space, over a single timestep, including applying any resulting angular torque.

Forces are useful for effects like gravity, wind or rocket thrust, but can be difficult in practice when precise control is needed. In these cases see Body.setVelocity and Body.setPosition as an alternative.

The force from this function is only applied once for the duration of a single timestep, in other words the duration depends directly on the current engine update delta and the rate of calls to this function.

Therefore to account for time, you should apply the force constantly over as many engine updates as equivalent to the intended duration.

If all or part of the force duration is some fraction of a timestep, first multiply the force by duration / timestep.

The force origin position in world-space must also be specified. Passing body.position will result in zero angular effect as the force origin would be at the centre of mass.

The body will take time to accelerate under a force, the resulting effect depends on duration of the force, the body mass and other forces on the body including friction combined.

Parameters

  • body Body
  • position Vector

    The force origin in world-space. Pass body.position to avoid angular torque.

  • force Vector

Matter.Body.create

(options)
Body

Creates a new rigid body model. The options parameter is an object that specifies any properties you wish to override the defaults. All properties have default values, and many are pre-calculated automatically based on other properties. Vertices must be specified in clockwise order. See the properties section below for detailed information on what you can pass via the options object.

Parameters

Returns

Body

body

Matter.Body.getAngularSpeed

(body)
Number

Gets the current rotational speed of the body.
Equivalent to the magnitude of its angular velocity.

Parameters

Returns

Number

angular speed

Matter.Body.getAngularVelocity

(body)
Number

Gets the current rotational velocity of the body.

Parameters

Returns

Number

angular velocity

Matter.Body.getSpeed

(body)
Number

Gets the current linear speed of the body.
Equivalent to the magnitude of its velocity.

Parameters

Returns

Number

speed

Matter.Body.getVelocity

(body)
Vector

Gets the current linear velocity of the body.

Parameters

Returns

Vector

velocity

Matter.Body.nextCategory

()
Number

Returns the next unique category bitfield (starting after the initial default category 0x0001). There are 32 available. See body.collisionFilter for more information.

Returns

Number

Unique category bitfield

Matter.Body.nextGroup

([isNonColliding=false])
Number

Returns the next unique group index for which bodies will collide. If isNonColliding is true, returns the next unique group index for which bodies will not collide. See body.collisionFilter for more information.

Parameters

  • [isNonColliding=false] Bool optional

Returns

Number

Unique group index

Matter.Body.rotate

(body, rotation, [point], [updateVelocity=false])

Rotates a body by a given angle relative to its current angle. By default angular velocity is unchanged. If updateVelocity is true then angular velocity is inferred from the change in angle.

Parameters

Matter.Body.scale

(body, scaleX, scaleY, [point])

Scales the body, including updating physical properties (mass, area, axes, inertia), from a world-space point (default is body centre).

Parameters

Matter.Body.set

(body, settings, value)

Given a property and a value (or map of), sets the property(s) on the body, using the appropriate setter functions if they exist. Prefer to use the actual setter functions in performance critical situations.

Parameters

  • body Body
  • settings Object

    A property name (or map of properties and values) to set on the body.

  • value Object

    The value to set if settings is a single property name.

Matter.Body.setAngle

(body, angle, [updateVelocity=false])

Sets the angle of the body. By default angular velocity is unchanged. If updateVelocity is true then angular velocity is inferred from the change in angle.

Parameters

Matter.Body.setAngularSpeed

(body, speed)

Sets the current rotational speed of the body.
Direction is maintained. Affects body angular velocity.

Parameters

Matter.Body.setAngularVelocity

(body, velocity)

Sets the current rotational velocity of the body.
Affects body angular speed.

Parameters

Matter.Body.setCentre

(body, centre, relative)

Set the centre of mass of the body. The centre is a vector in world-space unless relative is set, in which case it is a translation. The centre of mass is the point the body rotates about and can be used to simulate non-uniform density. This is equal to moving body.position but not the body.vertices. Invalid if the centre falls outside the body's convex hull.

Parameters

Matter.Body.setDensity

(body, density)

Sets the density of the body. Mass and inertia are automatically updated to reflect the change.

Parameters

Matter.Body.setInertia

(body, inertia)

Sets the moment of inertia of the body. This is the second moment of area in two dimensions. Inverse inertia is automatically updated to reflect the change. Mass is not changed.

Parameters

Matter.Body.setMass

(body, mass)

Sets the mass of the body. Inverse mass, density and inertia are automatically updated to reflect the change.

Parameters

Matter.Body.setParts

(body, parts, [autoHull=true])

Sets the parts of the body.

See body.parts for details and requirements on how parts are used.

See Bodies.fromVertices for a related utility.

This function updates body mass, inertia and centroid based on the parts geometry.
Sets each part.parent to be this body.

The convex hull is computed and set on this body (unless autoHull is false).
Automatically ensures that the first part in body.parts is the body.

Parameters

  • body Body
  • parts Body[]
  • [autoHull=true] Bool optional

Matter.Body.setPosition

(body, position, [updateVelocity=false])

Sets the position of the body. By default velocity is unchanged. If updateVelocity is true then velocity is inferred from the change in position.

Parameters

Matter.Body.setSpeed

(body, speed)

Sets the current linear speed of the body.
Direction is maintained. Affects body velocity.

Parameters

Matter.Body.setStatic

(body, isStatic)

Sets the body as static, including isStatic flag and setting mass and inertia to Infinity.

Parameters

  • body Body
  • isStatic Bool

Matter.Body.setVelocity

(body, velocity)

Sets the current linear velocity of the body.
Affects body speed.

Parameters

Matter.Body.setVertices

(body, vertices)

Sets the body's vertices and updates body properties accordingly, including inertia, area and mass (with respect to body.density). Vertices will be automatically transformed to be orientated around their centre of mass as the origin. They are then automatically translated to world space based on body.position.

The vertices argument should be passed as an array of Matter.Vector points (or a Matter.Vertices array). Vertices must form a convex hull. Concave vertices must be decomposed into convex parts.

Parameters

Matter.Body.translate

(body, translation, [updateVelocity=false])

Moves a body by a given vector relative to its current position. By default velocity is unchanged. If updateVelocity is true then velocity is inferred from the change in position.

Parameters

Matter.Body.update

(body, [deltaTime=16.666])

Performs an update by integrating the equations of motion on the body. This is applied every update by Matter.Engine automatically.

Parameters

Matter.Body.updateVelocities

(body)

Updates properties body.velocity, body.speed, body.angularVelocity and body.angularSpeed which are normalised in relation to Body._baseDelta.

Parameters

Properties / Options

The following properties if specified below are for objects created by Matter.Body.create and may be passed to it as options.

Body.angle

Number

A Number specifying the angle of the body, in radians.

Default: 0

Read only. Use Body.setAngularSpeed to set.

See Body.getAngularSpeed for details.

Default: 0

Read only. Use Body.setAngularVelocity to set.

See Body.getAngularVelocity for details.

Default: 0

Body.area

String

Read only. Calculated automatically when vertices are set.

A Number that measures the area of the body's convex hull.

Body.axes

Vector[]

Read only. Calculated automatically when vertices are set.

An array of unique axis vectors (edge normals) used for collision detection. These are automatically calculated when vertices are set. They are constantly updated by Body.update during the simulation.

Body.bounds

Bounds

A Bounds object that defines the AABB region for the body. It is automatically calculated when vertices are set and constantly updated by Body.update during simulation.

Body.chamfer

Object | Null | Undefined

Temporarily may hold parameters to be passed to Vertices.chamfer where supported by external functions.

See Vertices.chamfer for possible parameters this object may hold.

Currently only functions inside Matter.Bodies provide a utility using this property as a vertices pre-processing option.

Alternatively consider using Vertices.chamfer directly on vertices before passing them to a body creation function.

An Object that specifies the collision filtering properties of this body.

Collisions between two bodies will obey the following rules:

  • If the two bodies have the same non-zero value of collisionFilter.group, they will always collide if the value is positive, and they will never collide if the value is negative.
  • If the two bodies have different values of collisionFilter.group or if one (or both) of the bodies has a value of 0, then the category/mask rules apply as follows:

Each body belongs to a collision category, given by collisionFilter.category. This value is used as a bit field and the category should have only one bit set, meaning that the value of this property is a power of two in the range [1, 2^31]. Thus, there are 32 different collision categories available.

Each body also defines a collision bitmask, given by collisionFilter.mask which specifies the categories it collides with (the value is the bitwise AND value of all these categories).

Using the category/mask rules, two bodies A and B collide if each includes the other's category in its mask, i.e. (categoryA & maskB) !== 0 and (categoryB & maskA) !== 0 are both true.

A bit field that specifies the collision category this body belongs to. The category value should have only one bit set, for example 0x0001. This means there are up to 32 unique collision categories available. See body.collisionFilter for more information.

Default: 1

An Integer Number, that specifies the collision group this body belongs to. See body.collisionFilter for more information.

Default: 0

A bit mask that specifies the collision categories this body may collide with. See body.collisionFilter for more information.

Default: -1

Read only. Updated during engine update.

A Number that records the last delta time value used to update this body. Used to calculate speed and velocity.

Default: 1000 / 60

Read only. Use Body.setDensity to set.

A Number that defines the density of the body (mass per unit area).

Mass will also be updated when set.

Default: 0.001

Body.force

Vector

A Vector that accumulates the total force applied to the body for a single update. Force is zeroed after every Engine.update, so constant forces should be applied for every update they are needed. See also Body.applyForce.

Default: { x: 0, y: 0 }

A Number that defines the friction of the body. The value is always positive and is in the range (0, 1). A value of 0 means that the body may slide indefinitely. A value of 1 means the body may come to a stop almost instantly after a force is applied.

The effects of the value may be non-linear. High values may be unstable depending on the body. The engine uses a Coulomb friction model including static and kinetic friction. Note that collision response is based on pairs of bodies, and that friction values are combined with the following formula:

Math.min(bodyA.friction, bodyB.friction)

Default: 0.1

A Number that defines the air friction of the body (air resistance). A value of 0 means the body will never slow as it moves through space. The higher the value, the faster a body slows when moving through space. The effects of the value are non-linear.

Default: 0.01

A Number that defines the static friction of the body (in the Coulomb friction model). A value of 0 means the body will never 'stick' when it is nearly stationary and only dynamic friction is used. The higher the value (e.g. 10), the more force it will take to initially get the body moving when nearly stationary. This value is multiplied with the friction property to make it easier to change friction and maintain an appropriate amount of static friction.

Default: 0.5

Body.id

Number

An integer Number uniquely identifying number generated in Body.create by Common.nextId.

Read only. Automatically calculated when vertices, mass or density are set or set through Body.setInertia.

A Number that defines the moment of inertia of the body. This is the second moment of area in two dimensions.

Can be manually set to Infinity to prevent rotation of the body. See Body.setInertia.

Read only. Automatically calculated when vertices, mass or density are set or calculated by Body.setInertia.

A Number that defines the inverse moment of inertia of the body (1 / inertia).

Read only. Use Body.setMass to set.

A Number that defines the inverse mass of the body (1 / mass).

A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically.

Default: false

Read only. Use Sleeping.set to set.

A flag that indicates whether the body is considered sleeping. A sleeping body acts similar to a static body, except it is only temporary and can be awoken.

Default: false

Read only. Use Body.setStatic to set.

A flag that indicates whether a body is considered static. A static body can never change position or angle and is completely fixed.

Default: false

Body.label

String

An arbitrary String name to help the user identify and manage bodies.

Default: "Body"

Body.mass

Number

Read only. Use Body.setMass to set.

A Number that defines the mass of the body.

Density will also be updated when set.

Body.motion

Number

Read only. Calculated during engine update only when sleeping is enabled.

A Number that loosely measures the amount of movement a body currently has.

Derived from body.speed^2 + body.angularSpeed^2. See Sleeping.update.

Default: 0

Body.parent

Body

Read only. Updated by Body.setParts.

A reference to the body that this is a part of. See body.parts. This is a self reference if the body is not a part of another body.

Body.parts

Body[]

Read only. Use Body.setParts to set.

See Bodies.fromVertices for a related utility.

An array of bodies (the 'parts') that make up this body (the 'parent'). The first body in this array must always be a self-reference to this body.

The parts are fixed together and therefore perform as a single unified rigid body.

Parts in relation to each other are allowed to overlap, as well as form gaps or holes, so can be used to create complex concave bodies unlike when using a single part.

Use properties and functions on the parent body rather than on parts.

Outside of their geometry, most properties on parts are not considered or updated.
As such 'per-part' material properties among others are not currently considered.

Parts should be created specifically for their parent body.
Parts should not be shared or reused between bodies, only one parent is supported.
Parts should not have their own parts, they are not handled recursively.
Parts should not be added to the world directly or any other composite.
Parts own vertices must be convex and in clockwise order.

A body with more than one part is sometimes referred to as a 'compound' body.

Use Body.setParts when setting parts to ensure correct updates of all properties.

Body.plugin

An object reserved for storing plugin-specific properties.

Read only. Use Body.setPosition to set.

A Vector that specifies the current world-space position of the body.

Default: { x: 0, y: 0 }

Body.render

Object

An Object that defines the rendering properties to be consumed by the module Matter.Render.

A String that defines the fill style to use when rendering the body (if a sprite is not defined). It is the same as when using a canvas, so it accepts CSS style property values.

Default: a random colour

A Number that defines the line width to use when rendering the body outline (if a sprite is not defined). A value of 0 means no outline will be rendered.

Default: 0

Sets the opacity to use when rendering.

Default: 1

An Object that defines the sprite properties to use when rendering, if any.

An String that defines the path to the image to use as the sprite texture, if any.

A Number that defines the offset in the x-axis for the sprite (normalised by texture width).

Default: 0

A Number that defines the scaling in the x-axis for the sprite, if any.

Default: 1

A Number that defines the offset in the y-axis for the sprite (normalised by texture height).

Default: 0

A Number that defines the scaling in the y-axis for the sprite, if any.

Default: 1

A String that defines the stroke style to use when rendering the body outline (if a sprite is not defined). It is the same as when using a canvas, so it accepts CSS style property values.

Default: a random colour

A flag that indicates if the body should be rendered.

Default: true

A Number that defines the restitution (elasticity) of the body. The value is always positive and is in the range (0, 1). A value of 0 means collisions may be perfectly inelastic and no bouncing may occur. A value of 0.8 means the body may bounce back with approximately 80% of its kinetic energy. Note that collision response is based on pairs of bodies, and that restitution values are combined with the following formula:

Math.max(bodyA.restitution, bodyB.restitution)

Default: 0

A Number that defines the length of time during which this body must have near-zero velocity before it is set as sleeping by the Matter.Sleeping module (if sleeping is enabled by the engine).

Default: 60

Body.slop

Number

A Number that specifies a thin boundary around the body where it is allowed to slightly sink into other bodies.

This is required for proper collision response, including friction and restitution effects.

The default should generally suffice in most cases. You may need to decrease this value for very small bodies that are nearing the default value in scale.

Default: 0.05

Body.speed

Number

Read only. Use Body.setSpeed to set.

See Body.getSpeed for details.

Equivalent to the magnitude of body.velocity (always positive).

Default: 0

A Number that specifies per-body time scaling.

Default: 1

Body.torque

Number

A Number that accumulates the total torque (turning force) applied to the body for a single update. See also Body.applyForce. Torque is zeroed after every Engine.update, so constant torques should be applied for every update they are needed.

Torques result in angular acceleration on every update, which depends on body inertia and the engine update delta.

Default: 0

Body.type

String

Read only. Set by Body.create.

A String denoting the type of object.

Default: "body"

Read only. Use Body.setVelocity to set.

See Body.getVelocity for details.

Equivalent to the magnitude of body.angularVelocity (always positive).

Default: { x: 0, y: 0 }

Read only. Use Body.setVertices or Body.setParts to set. See also Bodies.fromVertices.

An array of Vector objects that specify the convex hull of the rigid body. These should be provided about the origin (0, 0). E.g.

[{ x: 0, y: 0 }, { x: 25, y: 50 }, { x: 50, y: 0 }]

Vertices must always be convex, in clockwise order and must not contain any duplicate points.

Concave vertices should be decomposed into convex parts, see Bodies.fromVertices and Body.setParts.

When set the vertices are translated such that body.position is at the centre of mass. Many other body properties are automatically calculated from these vertices when set including density, area and inertia.

The module Matter.Vertices contains useful methods for working with vertices.

Events

The following events are emitted by objects created by Matter.Body.create and received by objects that have subscribed using Matter.Events.on.

Events.on(Body, "sleepEnd", callback)

Fired when a body ends sleeping (where this is the body).

Callback Parameters

  • event Object

    An event object

    • source

      The source object of the event

    • name

      The name of the event

Events.on(Body, "sleepStart", callback)

Fired when a body starts sleeping (where this is the body).

Callback Parameters

  • event Object

    An event object

    • source

      The source object of the event

    • name

      The name of the event