Hey guys i\'m making a 2D java game and i\'m trying to figure out how to make a good collision code. I am currently using the following code:
public void che
Your main problem is in assuming that the player is running directly into the wall. Consider the case where there is a wall rect (100,100,32,32) and the player is at (80,68,32,32). The player is moving down and to the left, so player.xspeed < 0 and player.yspeed > 0; say the next position for the player is (79,69,32,32). The intersection is then (100,100,11,1).
Note that although the player is moving left (as well as down) the wall is actually to the right of the player. This line:
if (player.xspeed < 0) {
player.x += intersection.getWidth();
}
... causes player.x to be set to 90 in a sudden jump.
One thing you could do is check that the player's left-hand side was contained in the intersection, i.e.
if (player.xspeed < 0 && player.x >= intersection.x) {
player.x += intersection.getWidth();
}
Obviously a similar thing needs to be done for the other directions too.