How to Set Fixture Density in Planck.js
This article provides a straightforward guide on how to configure the density of a fixture in planck.js, a 2D JavaScript physics engine based on Box2D. You will learn how to define density during fixture creation using a fixture definition, how to adjust it on an existing fixture, and why updating mass properties is essential after making changes.
Setting Density During Fixture Creation
The most common way to set a fixture’s density is when you first
attach it to a body. When creating a fixture, you can pass a
configuration object (a fixture definition) that includes the
density property.
const planck = require('planck-js');
// 1. Create a world and a dynamic body
const world = planck.World();
const body = world.createBody({ type: 'dynamic' });
// 2. Define the shape
const shape = planck.Box(1.0, 1.0);
// 3. Create the fixture with a specific density
const fixture = body.createFixture({
shape: shape,
density: 2.5 // Density set to 2.5 kg/m²
});Changing Density on an Existing Fixture
If you need to alter the physical properties of an object during
simulation runtime, planck.js allows you to modify the density of a
fixture directly using the setDensity() method.
// Modify the density of an existing fixture
fixture.setDensity(5.0);Critical Step: Resetting Mass Data
Modifying a fixture’s density with setDensity() does not
automatically recalculate the overall mass of the parent rigid body. If
you change the density after the body has been created, you must call
resetMassData() on the body. This forces planck.js to
recalculate the body’s total mass and rotational inertia based on its
current fixtures.
// Update the fixture density
fixture.setDensity(5.0);
// Crucial: Recalculate the body's mass properties
body.resetMassData();Without calling body.resetMassData(), the body will
continue to behave as if it has its original mass, even though the
fixture’s internal density value has changed.