Skip to content

Instantly share code, notes, and snippets.

@dreasgrech
dreasgrech / ResolvingMatterCollisionsInPhaser3.js
Last active September 26, 2023 09:14
Resolving collisions using Matter physics with Phaser 3 in constant O(1) time
/*
This code shows how to resolve collisions using Matter physics with Phaser 3 in constant O(1) time.
Going through all the collision pairs is still linear O(n) time depending on how many collisions happened this frame
but the code that handles the resolution of the collision is constant and will not change with the total number of CollisionCategories / collision-lookups.
The way the code works is by generating a number based on the each of the collision combinations, use that number as a key for storing a pointer to the respective collision handler function,
and then when a collision happens, calculate the number again of both bodies' collision categories and use that number to fetch the collision handler function. Simple.
// dreasgrech - https://github.com/dreasgrech/
*/