【问题标题】:Matter.js - How to remove bodies after collisionMatter.js - 如何在碰撞后移除身体
【发布时间】:2023-04-07 07:39:01
【问题描述】:

我是 Matter.js 的新手,我真的很困惑如何在碰撞后删除一对中的特定主体,这是我的代码:

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);
    }
  }
});

我想在与球发生碰撞后删除方块,但代码不起作用。

【问题讨论】:

    标签: javascript matter.js


    【解决方案1】:

    看看这段代码。这应该可行!

    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);
    

    顺便说一句,不要使用 for 循环。 Foreach 与 matter.js 配合良好。

    【讨论】:

    【解决方案2】:
    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);
      });
    });
    

    应该有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-24
      • 2013-08-05
      相关资源
      最近更新 更多