I'm writing a top down 2d XNA game. Since its my first I'm trying to write the physics and collision stuff myself to learn it.
Whenever my player sprite character attempts to move into a position where its bounds intersect with the edge of a wall, I figure out a bounce angle (angle of incidence = angle of reflection) and I make the player bounce off the wall and avoid the collision.
I'm having trouble figuring out how to deal with the situation of my sprite intersecting with two wall edges simultaneously though e.g. it hits a corner.
My code currently tells me that two wall edges have been intersected but not which edge it would have hit first and therefore which edge to bounce off.
What is the mathematical test to pick which edge to bounce off? It's plain to see when looking at it but I'm struggling to figure out the math test for it.
Answer
If you calculate how far into the Wall
the Player Sprite
has moved, you can probably base it on the delta of the x and y coordinates of the corners that are intersecting. I hope that makes sense, I can't think of a better way to word it.
So, for example, if you look at your diagram. Take the x
value of the top left corner of the Player Sprite
(after the move), and subtract the x
value of the bottom right corner of the Wall
. Do the same thing for the y
values and then see which one is larger. The key is that if one is larger than the other, the Player Sprite
probably intersected on that side.
Here's an image example (this is a subsection of your image with my own lines added):
Now, you see here that the blue line is larger than the green line. In this case the blue line is also on the side that the Player Sprite
would be expected to bounce off of.
If the two values are equal, they hit right on the corner.
Now, there is a slight problem with doing it this way. If the Player Sprite
is traveling very fast or the collision is very close to the corner, it's possible that the Player Sprite
may go further into the Wall
in the wrong direction. In that case you'll probably have to check the velocity of the moving object. (See Nathan Reed's answer.)
Note: I think I'm essentially trying to describe the SAT collision detection that @Blau mentioned, but I've spent a long time writing this so I'm going to post it anyways. Hopefully it'll help you some.
No comments:
Post a Comment