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 badges3 Answers
Reset to default 3Have 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);
}
});
});