Resolving collisions using Matter physics with Phaser 3 in constant O(1) time

This code shows how to resolve Matter collisions using Phaser in a fast way.

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 O(1) and will not change with the total number of CollisionCategories / collision-lookups.

The gist of the gist is that it works by generating a number based on the each of the collision combinations, using 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.

The full code is in the gist but here’s a preview of how it works: