Matter.js - 碰撞后如何移除物体

问题描述 投票:2回答:2

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

Matter.Events.on(engine, 'collisonEnd', 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
2个回答
0
投票
Matter.Events.on(e, 'collisonEnd', ({ pairs }) => {
   pairs.forEach(({ bodyA, bodyB }) => {
     if (bodyA !== ball) Matter.World.remove(world, bodyA);
     if (bodyB !== ball) Matter.World.remove(world, bodyB);
  });
});

应该有所帮助


-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, 'collisonEnd', _ => {
    _.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不使用for循环。 Foreach适用于matter.js

问候。

© www.soinside.com 2019 - 2024. All rights reserved.