Collision Detection

The final and hardest part of the physics component is collision detection.

I use AABB collision detection to see if any object with a physics component is colliding with any object in the scene and provide the correct response depending on the collision.

Each physics component is given an array of all the sprite components in the scene which is passed into the collision function. This function goes through all the blocks four times for up, down, left and right collisions. The function then sets a bool passed in by ref to true if it collides on that side. Such as the in_left bool is set to true when the current object is colliding to the left of another. These bools are used in different mechanics that need to know about these collisions. The function itself also checks these bools for collisions to provide the correct response. The number of types of collision responses got very extensive and most of them are relative to the current direction of gravity. This meant that these responses were double but in different directions depending on gravity’s direction. The function returned the index of the block the user was currently colliding underneath with (or above if gravity was upwards) so that the block’s corresponding amount of friction could be found and given to the momentum functions.

 

Post Mortem

This collision detection system overall felt too expensive. Each component had to iterate through all the objects 4 times every frame. In the future, I would do all collision detection within the update of the game scene not each object in their physics component. Also since the code base is using a component-based design pattern for its gameObjects the physics component needed the sprite components all the blocks since that’s where its colliders are stored. In future development using a component-based design pattern, I will use a collider component to store the colliders otherwise collision only works if a game object also has a sprite.

Previous
Previous

Global Gravity Flip and Jumping

Next
Next

Momentum based movement