Assign Custom Labels to Bodies in Matter.js

In Matter.js, assigning a custom label to a rigid body allows you to easily identify, categorize, and filter objects during collision detection and simulation updates. This guide demonstrates how to define the built-in label property during body creation, how to update it dynamically at runtime, and how to use it inside collision event listeners to run specific game logic.

Setting a Label During Body Creation

Every body factory method in the Matter.Bodies module accepts an optional options configuration object. You can assign your custom identifier by passing a string value to the label property within this object.

const { Bodies } = Matter;

// Create a body with a custom label
const player = Bodies.rectangle(100, 200, 50, 50, {
    label: 'playerBody',
    isStatic: false
});

const ground = Bodies.rectangle(400, 600, 800, 50, {
    label: 'groundBody',
    isStatic: true
});

Updating a Label Dynamically

Matter.js exposes the label property directly on the instantiated Body object. If your game or simulation state changes, you can reassign the label at any time.

// Reassign the label directly on the instance
player.label = 'invinciblePlayer';

Using Custom Labels in Collision Events

Custom labels are most commonly used to detect and handle collisions between specific types of bodies. You can listen for collision events on the engine and inspect the label properties of the colliding pair.

const { Events } = Matter;

Events.on(engine, 'collisionStart', (event) => {
    event.pairs.forEach((pair) => {
        const { bodyA, bodyB } = pair;

        // Check if the collision involves a player and the ground
        if (
            (bodyA.label === 'playerBody' && bodyB.label === 'groundBody') ||
            (bodyB.label === 'playerBody' && bodyA.label === 'groundBody')
        ) {
            console.log('Player landed on the ground.');
        }
    });
});

Adding Custom Properties Beyond Labels

If a single string label is not sufficient for your application, Matter.js allows you to pass arbitrary key-value pairs inside the initial options object or attach properties directly to the body instance.

const enemy = Bodies.circle(300, 200, 20, {
    label: 'enemy',
    health: 100,
    faction: 'hostile'
});

console.log(enemy.health); // 100