简体   繁体   English

Java 2D碰撞?

[英]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. 大家好,我正在制作2D Java游戏,并且我试图找出如何制作良好的碰撞代码。 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 types of maps I have: 这是我拥有的地图类型的图片:

在此处输入图片说明

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). 考虑以下情况:有墙角(100,100,32,32),玩家在(80,68,32,32)。 The player is moving down and to the left, so player.xspeed < 0 and player.yspeed > 0; 播放器正在向左和向左移动,因此player.xspeed <0和player.yspeed> 0; say the next position for the player is (79,69,32,32). 假设玩家的下一个位置是(79,69,32,32)。 The intersection is then (100,100,11,1). 则交点为(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. ...导致将player.x突然设置为90。

One thing you could do is check that the player's left-hand side was contained in the intersection, ie 您可以做的一件事是检查玩家的左侧是否包含在路口中,即

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. 显然,其他方向也需要做类似的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM