I'm using MatterJS to animate some objects on a canvas. At one point in the animation there is a collision between two of my objects. I'm successfully detecting the event with the below code:
Events.on(engine, 'collisionStart', function(event) {
console.log(event)
});
What i'm trying to identify is which two objects are colliding. When I console.log event.pairs I get an empty array. I would have thought it would have returned an array of the two objects that are colliding. Where have I gone wrong?
I'm using MatterJS to animate some objects on a canvas. At one point in the animation there is a collision between two of my objects. I'm successfully detecting the event with the below code:
Events.on(engine, 'collisionStart', function(event) {
console.log(event)
});
What i'm trying to identify is which two objects are colliding. When I console.log event.pairs I get an empty array. I would have thought it would have returned an array of the two objects that are colliding. Where have I gone wrong?
Share Improve this question asked Jul 24, 2017 at 13:11 red house 87red house 87 2,42512 gold badges61 silver badges110 bronze badges 1- Likely a dupe of console log event object shows different object properties than it should have – ggorlen Commented Dec 24, 2022 at 19:02
3 Answers
Reset to default 5You Really have no errors. you must see your pair on position zero, the library matterjs have a problem printing this value from event main. you must deploy your response and you will able to see your pairs, so:
Events.on(engine, 'collisionStart', function(event) {
console.log("Evento: ", event)
var pairs = event.pairs;
console.log("Pair no visible: ", pairs)
console.log("Pair visible: ", pairs[0]);
console.log("colision between " + pairs[0].bodyA.label + " - " + pairs[0].bodyB.label);
});
Here, i am showing a simple example.
Complementing answer of Cristian Agudelo, you need to copy state of pairs and then do what you want:
Matter.Events.on(engine, "collisionStart", function(e)
{
var pairs = e.pairs.slice(); // copy
...
}
in order to successfully work with collisions in Matter js, try to access each pair of the returned array from the event object.
Events.on(engine, 'collisionStart', (event) => {
event.pairs.forEach((collision) => {
console.log(collision);
});
});