Using XNA's built in Intersects() on two Rectangles, I can detect a collision and set my velocity to zero. However, the object is stuck there and can't get out! How can I resolve this collision properly?
This is because once your object gets into the wall and you find the collision, you're simply stopping the object's movement by setting its velocity to zero, but the object is still within that wall.
To fix it, you have to resolve the collision by moving the object. You have two options here:
Implementation of second option
Here I'll assume that the velocity represents the direction in which the object is going (basically that you are not changing the velocity between the object's position change and the collision check). I'll also assume that your origin is positioned at the top-left of the image (so when moving the object to resolve the collision I'll position the top-left corner).
Here is how I would do:
You could also use the old object's position to find where the object is from, but using the velocity is simpler in this case.
|show 10 more comments|
You can do this in various ways.
One method is storing the previous position of the Rectangle every frame. So, when your rectangles Intersects, just set the object position to the older one that not collided. This method is not the best, because if the Rectangle velocity is high, you may see the reposition that you made via code.
Another method is testing the collision with a Raycast, so you can preview a collision before it ever happens.
Take a look at msdn for documentation for Raycast collision, and you'll be able to do that.