Hello guys,
I'm working on a personal platform game using this library and wanted to know what is the best way to remove a body from the world.
Let me explain my use case, I'm creating two squares, let's say the first one is the player and the second one is a reward. I want to remove the reward after the player collides. That's easy using Matter.World.remove method because disappear from the game but the player still collides when going to the reward position again and again.
The following code shows how I build the items and check if player and reward collide:
let view = Matter.Composite.create();
let box = Matter.Bodies.rectangle(400, 400, 600, 20, { isStatic: true });
let player = Matter.Bodies.rectangle(400, 300, 50, 20);
let reward = Matter.Bodies.rectangle(650, 300, 30, 30);
Matter.Composite.add(view, [box, player, reward]);
Matter.World.add(engine.world, view);
Matter.Events.on(engine, 'afterUpdate', function() {
let collisions = Matter.Query.collides(player, [reward]);
if(collisions.length > 0) {
console.log('keep colliding'); // shows the message even after the reward item has been removed
Matter.Composite.remove(view, reward);
}
});
Is it a better way to remove items from Composite or World items? Is there something that I'm missing and to be updated in some way?
Regards
I don't think Matter.Query.collides checks if the body is in the world, that could be the problem. If so an easy fix would be to set a flag on it after you remove it and check for that before the collision.
That said I'd recommend looking at the engine collisionStart event which will only include collisions for bodies in the world.
I tried both solutions and worked fine. Personally, I think the proper one is to use the collisionStart event, seems to be more elegant isn't it?
Thanks @liabru