Physics
Coral Engine has a custom 2D physics system. While the system was created by Amzy, I made various contributions over the course of development.
BVH
We were hoping to create a game with thousands of enemies and even more colliders. Our brute-force approach would no longer hold up. I have written a BVH before for my ray tracing project, and used my old code and knowledge to optimise the physics in Coral Engine.
The physics were now more than fast enough to suit our needs. Even with the many colliders in our benchmarks and final game, we did not experience physics to be a performance bottleneck.
Terrain height
We wanted to have a level with vertical elements, but our physics system only supported 2 dimensions. I worked on adding another dimension to our physics system.
We have a very simple physics implementation. One constraint we have is that all of our colliders are 2D; the user does not need to specify the height of a cylinder. But now that we would be walking on the terrain, we need to know the height of the colliders beneath our feet.
I decided to use a very simple approach; iterating over the colliders, getting the height of the collider based only on its position, and then choosing the highest collider that overlaps the given 2D point.
The problem is that we then need to transform the colliders to world-space, and calculating tens of thousands of matrices every frame slowed our program down immensely. In order to make this method viable, I made sure to optimise the physics system by creating TransformedColliders; each collision shape is ‘transformed’ once every frame, for example each AABBCollisionShape will update their corresponding TransformedAABBCollisionShape only once per frame.
Once we had a relatively efficient way of obtaining the height at a given position, the rest of the system was a series of small adjustments; only allowing physics bodies to move if the height at the current position roughly matched the height at their desired position.
The final result?
Our new physics system allowed for the creation of more interesting levels. As a bonus, the physics had become significantly faster overall, mainly due to the introduction of AABBs serving as early outs for polygon checks, and by only transforming the colliders once per frame.