use*_*238 5 javascript matter.js
我是 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);
}
}
});
Run Code Online (Sandbox Code Playgroud)
我想在与球碰撞后删除方块,但代码不起作用。
看看这段代码。这应该有效!
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);
Run Code Online (Sandbox Code Playgroud)
顺便说一句,不要使用 for 循环。Foreach 与 Matter.js 配合得很好。