I want a way to see if my player (which is a box) is colliding with another body from the world, any other body than my player.
I didn't find a way to do it in the documentation, only in pair or in a list. But if I put the entire world in the list, it's going to count other collisions without the player.
You can use
Matter.Query.collides(boxBody, arrayOfAllOtherEntitiesExceptBoxBody)
. By excluding the player box from the second parameter collision array, there won't be a false positive self-collision on the player box.Query.collides()
returns an array of collisions, so it may be a bit expensive if you just need a boolean (I'm not sure how it's actually implemented, just a guess. It's good not to prematurely optimize).Matter.Events.on(engine, "collisionStart", cb)
can be used as an alternative. In the callback, iterate the colliding body pairs to see if any are the player.If use
Query.collides()
, you'll likely run it oncollisionStart
andcollisionEnd
rather thanbeforeUpdate
to avoid running it more than necessary.Here's a minimal example illustrating both techniques. Use the mouse to move the player.
Yet another option is to tap into the
collisionActive
event. Here's an example that would work in the above code:.some()
can be used instead of.find()
if you only care about getting the boolean. Or if you want an array of all collisions between the player and other bodies: