Published on

Matter.js Collisions Explained

Thumbnail

Matter.js is a 2D physics engine for the web.

Although it is not as sophisticated as other engines, it is good enough to demonstrate simple physics stuff.

CodeSandbox Example

Collisions

If you want to determine whether the objects collide or not, you need to use the collisionFilter property when creating bodies.

We need to know two properties: category and mask to understand how collisions work in Matter.js.

Category

We need to create collision categories. Categories should be a bit field. There are up to 32 unique categories that you can specify.

Example categories are:

0x0001 0x0002 0x0004 0x0008 0x0010

Mask

You add categories to the mask property. If you do not add anything, the body will collide with everything.

Example

Let's create three different categories.

var defaultCategory = 0x0001, // for walls
  redCategory = 0x0002, // red circles
  yellowCategory = 0x0004 // yellow circles

When I create red circles, I specify their categories as redCategory

Bodies.circle(x, y, 20, {
  collisionFilter: {
    category: redCategory,
  },
  render: {
    strokeStyle: 'red'
    fillStyle: 'transparent',
    lineWidth: 1,
  },
})

The same thing applies when I create yellow circles. They have the yellowCategory

Bodies.circle(x, y, 20, {
  collisionFilter: {
    category: yellowCategory,
  },
  render: {
    strokeStyle: 'yellow',
    fillStyle: 'transparent',
    lineWidth: 1,
  },
})

Now, we have red and yellow circles. They collide with each other as they do not have a mask property inside collisionFilter

We can add a mask property if we want to create a circle that collides with walls and yellow circles but not red ones.

Bodies.circle(310, 40, 30, {
  collisionFilter: {
    mask: defaultCategory | yellowCategory,
  },
  render: {
    fillStyle: 'blue',
  },
})

This circle will not collide with redCategory as redCategory is not inside the mask.