How to Attach a Fixture to a Body in planck.js?

In planck.js (the JavaScript rewriting of the Box2D physics engine), attaching a fixture to a rigid body requires creating a body definition, instantiating the body within the world, defining a geometric shape, and finally binding that shape to the body using a fixture definition. This process defines the physical properties of the object, such as its shape, density, and friction. By understanding the relationship between worlds, bodies, shapes, and fixtures, you can easily construct complex physical simulations in your JavaScript applications.

1. Create the World and the Body

Before you can attach a fixture, you need a physics world and a rigid body. The world manages the simulation, while the body serves as the structural entity that holds the physical properties.

const planck = require('planck-js');

// Initialize the physics world with gravity
const world = planck.World({
  gravity: planck.Vec2(0, -10)
});

// Create a dynamic body at a specific position
const body = world.createBody({
  type: 'dynamic',
  position: planck.Vec2(0, 5)
});

2. Define the Shape of the Fixture

A fixture cannot exist without a geometry. You must define a shape, such as a box, circle, or polygon, to determine the physical boundaries of the object.

// Define a box shape (2 meters wide, 2 meters high total)
const shape = planck.Box(1.0, 1.0);

3. Attach the Fixture to the Body

There are two main methods to attach a fixture to your body depending on how much control you need over the physical properties like density, friction, and restitution.

Method A: Direct Attachment (Quick Method)

If you only need to assign a shape with default material properties, you can pass the shape directly to the body’s createFixture method.

// Attaches the shape with default density (0.0)
body.createFixture(shape);

Method B: Configuration Object (Advanced Method)

To customize properties like how heavy the object is (density) or how bouncy it is (restitution), pass a configuration object containing the shape.

// Attaches the shape with custom physical properties
body.createFixture({
  shape: shape,
  density: 1.0,
  friction: 0.3,
  restitution: 0.5
});

Summary of Key Fixture Properties

When attaching a fixture using the configuration object, you can fine-tune the behavior using these parameters: