最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Matter.js - How to remove bodies after collision - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question edited May 15, 2020 at 21:17 Mikhail 9,0079 gold badges57 silver badges87 bronze badges asked Nov 9, 2017 at 16:56 user8108238user8108238 792 silver badges4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

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

Matter.World is now deprecated, so you should use Matter.Composite:

Matter.Events.on(engine, "collisionEnd", (event) => {
  event.pairs.forEach(({ bodyA, bodyB }) => {
    if (bodyA !== ball) {
      Matter.Composite.remove(engine.world, bodyA);
    }
    if (bodyB !== ball) {
      Matter.Composite.remove(engine.world, bodyB);
    } 
  });
});
发布评论

评论列表(0)

  1. 暂无评论