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?
Answer
The usual approach for collision detection is to not have either A or B detect collisions on their own.
Instead, you first move all objects, then have a separate collision system look for collisions between all pairs of objects, telling every object about the things that it has collided with, and then finally render all objects.
So in essence, instead of doing "move, check for collisions, draw" inside your Paint() function, you split up "move" and "draw" into separate functions which you call separately (first "move" for every object, then "draw" for every object). And between those, check for collisions.
Advanced note: If any of your objects move themselves in reaction to detected collisions, then you may need to repeat the "look for collisions between all pairs of objects" step, in case an object's collision-response causes another collision.
No comments:
Post a Comment