How to Assign Collision Categories in Matter.js
This guide explains how to control object interactions in Matter.js using collision categories and masks. By utilizing 32-bit integer bitmasks, Matter.js allows you to define distinct collision layers for bodies, determine which groups of bodies can collide, and specify which ones will pass through each other. You will learn how to define categories, assign them to bodies, and configure collision masks effectively.
Understanding Collision Filters
Matter.js controls body collisions through the
collisionFilter property on each body. This property relies
on two primary fields:
category: A bitmask representing the group to which the body belongs.mask: A bitmask specifying which categories this body is permitted to collide with.
By default, every body in Matter.js has a category of
0x0001 and a mask of 0xFFFFFFFF
(which means it collides with everything).
Step 1: Define Your Categories
Because categories are evaluated using bitwise operations, each distinct category must be a power of 2 (up to 32 unique categories). Define them using hexadecimal notation for clarity:
const defaultCategory = 0x0001;
const redCategory = 0x0002;
const blueCategory = 0x0004;
const greenCategory = 0x0008;Step 2: Assign a Category to a Body
You can assign a category when creating a body by passing
collisionFilter in the options object:
const redBox = Matter.Bodies.rectangle(100, 200, 50, 50, {
collisionFilter: {
category: redCategory
}
});To update an existing body's category later:
redBox.collisionFilter.category = redCategory;Step 3: Configure Collision Masks
For two bodies (Body A and Body B) to collide, both of the following bitwise conditions must be true:
(bodyA.collisionFilter.category & bodyB.collisionFilter.mask) !== 0
(bodyB.collisionFilter.category & bodyA.collisionFilter.mask) !== 0To configure which categories a body can hit, set its
mask. Use the bitwise OR operator (|) to allow
collisions with multiple categories:
// This body belongs to redCategory and only collides with blueCategory and greenCategory
const redBox = Matter.Bodies.rectangle(100, 200, 50, 50, {
collisionFilter: {
category: redCategory,
mask: blueCategory | greenCategory
}
});
// This body belongs to blueCategory and collides with redCategory
const blueBox = Matter.Bodies.rectangle(100, 400, 50, 50, {
collisionFilter: {
category: blueCategory,
mask: redCategory
}
});In this setup, redBox and blueBox will
collide with each other. If another object belongs to
redCategory, redBox will pass directly through
it because redCategory is omitted from
redBox.collisionFilter.mask.