Search code examples
javascriptmatter.js

How do I prevent collision between bodies in a stack using MatterJS?


Using MatterJS I have a stack of circles and a floor rectangle:

var stack = Composites.stack(300, 0, 3, 3, 10, 10, function(x, y) {
    return Bodies.circle(x, y, Common.random(10, 20), {friction: 0, restitution: 0.2, density: 0.001 });
}); 

Composite.add(world, stack);

Composite.add(world, [
    Bodies.rectangle(300, 300, 600, 20, { isStatic: true, friction: 0, render: { fillStyle: '#060a19' } }),
]); 

How do I make those circles ignore each other and only collide with my floor rectangle?


Solution

  • Based on this post, you can add the circles to the category 0b10 and mask them against 0b01. This disables the bit that allows them to collide with their own category.

    const engine = Matter.Engine.create();
    const stack = Matter.Composites.stack(
      // xx yy cols rows colGap rowGap
      300,  0, 3,   3,   10,    10,
      (x, y) =>
        Matter.Bodies.circle(x, y, Matter.Common.random(10, 20), {
          friction: 0,
          restitution: 0.2,
          density: 0.001,
          collisionFilter: {
            mask: 0xfffffd,
            category: 0b10,
          },
        })
    );
    const floor = Matter.Bodies.rectangle(300, 200, 600, 20, {
      isStatic: true,
    });
    Matter.Composite.add(engine.world, [stack, floor]);
    const render = Matter.Render.create({
      element: document.body,
      engine: engine,
      options: {
        width: 800,
        height: 600,
        showAngleIndicator: true,
      },
    });
    Matter.Render.run(render);
    const runner = Matter.Runner.create();
    Matter.Runner.run(runner, engine);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.20.0/matter.min.js"></script>