Collision detection using the pyhsics engine (Matter.js)

This is an easy ways 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.

2 Likes

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

2 Likes