Matter.js - How to remove bodies after collision

Viewed 5213

I'm new to Matter.js, I'm really confused about how to remove a specific body in the pair after a collision, here is my code:

Matter.Events.on(engine, 'collisionEnd', function(event){
  var i, pair,
  length = event.pairs.length;
  for(i = 0; i<length; i++){
    pair = event.pairs[i];
    if(pair.bodyA === ball){
      continue;
    }
    else{
      World.remove(world, pair.bodyA);
    }
  }
});

I want to delete the squares after having a collision with the ball, but the code isn't working.

2 Answers

Have a look on this code. This should work!

var e = Matter.Engine.create(document.body);
var a = Matter.Bodies.rectangle(400, 400, 100, 60);
var b = Matter.Bodies.rectangle(450, 100, 100, 60);

Matter.Events.on(e, 'collisionEnd', _ => {
    _.pairs.forEach(_ => {
        if(_.bodyA === a || _.bodyB === a)
            Matter.World.remove(e.world, a);
    });
});

Matter.World.add(e.world, [a, b]);
Matter.Engine.run(e);

BTW do not use for-loops. Foreach works fine with matter.js.

Matter.Events.on(e, 'collisionEnd', ({ pairs }) => {
   pairs.forEach(({ bodyA, bodyB }) => {
     if (bodyA !== ball) Matter.World.remove(world, bodyA);
     if (bodyB !== ball) Matter.World.remove(world, bodyB);
  });
});

should help

Related