开发者

Java 2D Collision?

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 checkCollision() {
    Rectangle player_rectangle = new Rectangle(player.getX(),player.getY(),32,32);

    for(Wall wall : walls) {

        Rectangle wall_rectangle = new Rectangle(wall.getX(), wall.getY(), 32,32);

        if (player_rectangle.intersects(wall_rectangle)) {
            Rectangle intersection = (Rectangle) player_rectangle.createIntersection(wall_rectangle);

            if (player.xspeed > 0) {
                player.x -= intersection.getWidth();
            }

            if (player.yspeed > 0) {
                player.y -= intersection.getHeight();
            }

            if (player.xspeed < 0) {
                player.x += intersection.getWidth();
            }

            if (player.yspeed < 0) {
                player.y += intersection.getHeight(); 
            }

            Print(Integer.toString(intersection.width) + ", " + Integer.toString(intersection.height));

        }

    }

}

With this code it works fine if you are press one button but if press down and left for example the player will fly off in some random direction.

Here is a picture of the t开发者_运维技巧ypes of maps I have:

Java 2D Collision?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜