Collision detection using the physics engine (Matter.js)

This is an easy way to detect collisions and get the members involved in the collision. This simple example doesn’t deregister the event handler so keep that in mind when switching scenes.

Code (reduced to essentials):

// Fetch physics engine for our hypeDocument
var hypeDocElm = document.getElementById(hypeDocument.documentId());
var engine = hypeDocument.getElementProperty(hypeDocElm, 'physics-engine') 
// Event listener
Matter.Events.on(engine, 'collisionStart', function(event) {
	// We know there was a collision so fetch involved elements ...
	var aElm = document.getElementById(event.pairs[0].bodyA.elementId);
	var bElm = document.getElementById(event.pairs[0].bodyB.elementId);
	// Now do something with the event and elements ... your task ;-)
});

Demo:
CollisionDetectionMatter.html

Source:
CollisionDetectionMatter.hype.zip

Have fun! Should be great for games!

PS: If you use this method in a game, make sure to post a link to it in this thread or maybe even share your source. That would be much appreciated.

5 Likes

i used the collisiondectection in the sea-horse-game :

4 Likes

Amazing! :star_struck:

Also have a look at which uses collisionstart to colour dominos as they each hit each other.


gah, and just realised this is an old post so you may already have..

1 Like