I am developing a small 2D game engine. The characters have a paint method which currently does the following:
- Calculate the new position of the character as per its speed, etc.
- Update the collision grid cell **
- Draw the character at the new position
** I have created a collision grid to reduce the number of intersection checks
Now the basic algorithm which I have thought for detecting collision is:
For Each Character Check intersection with characters in surrounding 8 cells
I can simply place this code in the paint method. But here is the problem I anticipate.
Suppose two characters A and B lie in adjacent cells in the collision grid. Now as per the above algorithm in the iteration of character A it will detect that it has collided with B. In the iteration for character B it will detect that it has collided with A.
But I have an idea that when A detects that it has collided with B, it should inform B that it has collided with A. This would save lot of comparisons when there are more than 2 actors colliding. But I am not sure how to handle this. I think instead of every character checking for its collision, I should check for the collision inside the game loop.
Would this approach be correct? How have you handled this kind of problem? I thought of the collision grid thing myself. Are there any alternatives to collision grid logic?