Java 2D的碰撞? [英] Java 2D Collision?

查看:259
本文介绍了Java 2D的碰撞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿家伙我正在做的2D Java小游戏,我试图找出如何使一个良好的碰撞code。我目前正在使用下面的code:

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));

        }

    }

}

通过这个$ C C $它正常工作,如果你是preSS一个按钮,但如果preSS向下和向左例如玩家将飞了出去,在一些随机的方向。

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:

推荐答案

您的主要问题是在假定播放器直接运行到墙上。考虑那里有一个壁矩形(100,100,32,32)和玩家是在(80,68,32,32)的情况。玩家被向下移动并到左边,所以player.xspeed&其中; 0和player.yspeed> 0;说为玩家下一个位置(79,69,32,32)。该路口是那么(100,100,11,1)。

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();
}

...导致player.x在突然跳被设置为90。

... 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.

这篇关于Java 2D的碰撞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆