How to Get Composite Body Mass in Planck.js

This article provides a straightforward guide on how to retrieve the total mass data of a composite body in planck.js. You will learn how to access the mass, center of mass, and rotational inertia of a body composed of multiple fixtures, along with a practical code example to implement in your 2D physics simulations.

Understanding Bodies and Fixtures in Planck.js

In planck.js (a 2D physics engine based on Box2D), a Body represents a rigid object in your simulation. A body itself does not have a shape; instead, you attach one or more Fixtures to it. When a body has multiple fixtures attached to it, it is considered a composite body.

Each fixture has its own shape and density. Planck.js automatically calculates the combined mass properties of the body based on the sum of all its attached fixtures.

Retrieving the Mass Data

To get the mass details of any body, you use the built-in getMassData() method. This method populates and returns an object containing three essential properties:

Code Example

Here is how you can set up a composite body and retrieve its total mass data:

// Assume 'world' is your planck.World instance
// 1. Create a dynamic body
const body = world.createBody({
  type: 'dynamic',
  position: pl.Vec2(0, 0)
});

// 2. Attach multiple fixtures to create a composite body
body.createFixture({
  shape: pl.Box(1.0, 1.0), // A square shape
  density: 1.0
});

body.createFixture({
  shape: pl.Circle(pl.Vec2(2.0, 0), 0.5), // An offset circle shape
  density: 2.0
});

// 3. Retrieve the combined mass data
const massData = {};
body.getMassData(massData);

// 4. Access the properties
console.log(`Total Mass: ${massData.mass}`);
console.log(`Center of Mass: X=${massData.center.x}, Y=${massData.center.y}`);
console.log(`Rotational Inertia: ${massData.I}`);

Alternative Direct Methods

If you only need the total mass value and do not require the center of mass or rotational inertia, planck.js provides a direct shortcut method:

const totalMass = body.getMass();
console.log(`Direct Total Mass: ${totalMass}`);

Using either getMassData(massData) or getMass() ensures you always get the up-to-date, aggregated mass of your composite physics objects.