Java 2D中的碰撞检测不能正常工作

时间:2016-09-29 20:12:13

标签: java 2d collision

所以基本上在过去一岁半的时间里,我一直试图让这个盒子(玩家)当他与另一个盒子相撞时,他停止朝着与盒子相撞的方向移动。它有点像成功但在看似随意的时刻,如果我向上移动并击中玩家左侧的方框,它可能会撞到它碰撞的盒子并飞下来。各个方向都是一样的。

public int checkCollision(ID id){
    for(int i = 0; i < handler.obj.size(); i++){ //Cycles through all the objects
        GameObject go = handler.obj.get(i); //Stores a temp GameObject
        if(go.getID() == id){ //Checks if the id matches and if so do the collision stuff.
            if(getBoundsT().intersects(go.getBounds())){
                System.out.println("collided top");
                y = go.getY() + go.getHeight();
                velY = 0;
                return 0; //Top side
            }
            if(getBoundsB().intersects(go.getBounds())){
                System.out.println("collided bottom");
                y = go.getY() - height;
                velY = 0;
                return 1; //Bottom side
            }
            if(getBoundsL().intersects(go.getBounds())){
                x = go.getX() + width;
                velX = 0;
                System.out.println("collided left");
                return 2; //Left Side
            }
            if(getBoundsR().intersects(go.getBounds())){
                System.out.println("collided right");
                x = go.getX() - width;
                velX = 0;
                return 3; //Right Side
            }
            if(getBounds().intersects(go.getBounds())){
                System.out.println("collided on all sides");
                return 4; //All the sides
            }
        }
    }
    return 5; //No Collision
}

checkCollision方法每秒调用60次。 getBounds(l / r / u / d)函数只返回与字母对应的左,右,上(上)或下(下)侧的矩形。 Id就是玩家与之碰撞的内容。在这种情况下它是墙,所以无论它在哪里说它只是墙。 (我确保矩形不会超出它们应该的区域。)

我已经尝试了所有我能想到的东西,所以任何帮助都会受到赞赏! (这是我的第一个问题,如果写的可怕的话,对不起)

编辑:相交代码(getBounds)这是所有对象都继承的GameObject类。

public Rectangle getBoundsB() {
        return new Rectangle((int)(x + (width/2) - (width/4)), (int)(y + height/2), (int)(width / 2), (int)(height / 2));
    }
    public Rectangle getBoundsT() {
        return new Rectangle((int)(x + (width/2) - (int)(width/4)), (int) y, (int)width / 2, (int)(height / 2));
    }
    public Rectangle getBoundsR() {
        return new Rectangle((int)(x + width - 5), (int)(y + 5), 5, (int)(height - 10));
    }
    public Rectangle getBoundsL() {
        return new Rectangle((int)x, (int)(y + 5), 5, (int)(height - 10));
    }

    public Rectangle getBounds() {
        return new Rectangle((int)x, (int)y, (int)width, (int)height);
    }

并在tick方法中(每60秒调用一次):

checkCollision(ID.Wall);

1 个答案:

答案 0 :(得分:1)

下图显示了矩形与墙壁的3个边。如果我将矩形按在墙上,蓝线和绿线的左角接触墙壁,红线接触墙壁。所以发生了什么是因为你首先检查顶部,它看到在那个单点有一个交叉点并且返回顶部交叉而不是左边的真。

enter image description here

我认为你可以修改这个修改你如何得到你的上/下限。也许通过从宽度中减去1来返回你的边界。

相关问题