簡體   English   中英

Java 2D 中的碰撞檢測無法正常工作

[英]Collision Detection in Java 2D Not Working Properly

所以基本上在過去的一個半年齡里,我一直試圖讓這個盒子人(玩家)當他與另一個盒子相撞時,他會停止向他與盒子相撞的方向移動。這有點成功,但在看似隨機的時刻,如果我向上移動並擊中玩家左側的盒子,它可能會撞到與之相撞的盒子中並飛下來。 每個方向都是一樣的。

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 就是玩家正在碰撞的東西。 在這種情況下,它是牆,所以無論它在哪里說 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);

下圖顯示了靠牆的矩形的 3 條邊。 如果我將矩形按在牆上,則藍綠線的左角接觸牆壁,紅線接觸牆壁。 所以發生的事情是因為你首先檢查頂部,它看到在那個單一的點有一個交點,並為頂部交點而不是左邊返回真。

在此處輸入圖片說明

我認為您可以通過修改獲得頂部/底部邊界的方式來解決此問題。 也許通過從返回邊界的寬度中減去 1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM