2014-09-29 68 views
-1

我正在構建一個基於2d瓦的遊戲,類似於塞爾達傳說遊戲,而我的碰撞方法無法正常工作。當玩家遠遠低於不可通行的瓦片時,該方法將返回碰撞。必須有一個我在這裏沒有看到的邏輯錯誤。這是用Java編寫的。碰撞法瘋了;

從靜態碰撞類:

public static boolean collisionAbovePlayer(TileGrid grid, float x, float y, int width, int height) { 
    boolean collision = false; 

    for (Tile[] row : grid.map) { 
     for (Tile t : row) { 

      // Each Tile t in map: 

      if (t.getType().getPassable() == false) { 

       // Each impassable tile: 

       if ( (x-t.getX() > 0 && x - t.getX() < t.getWidth()) || (x - t.getX() < 0 && Math.abs(x - t.getX()) < width)) { 

        // Tile is within collision x range 

        if ((t.getY() + t.getHeight() + 1) - y < Math.abs(5)) { 
         collision = true; 
        } else { 
         collision = false; 
        } 

       } else { 
        collision = false; 
       } 
      } 
     } 
    } 

    return collision; 
} 

這是我Player類被稱爲用這種方法(我還沒有實現對其他方向的碰撞方法還):

public void Update() { 
    if (first) 
     first = false; 
    else { 
     if ((Keyboard.isKeyDown(Keyboard.KEY_W)) && (!collisionAbovePlayer(grid, x, y, width, height))) { 
      y -= Delta() * speed; 
     } 
     if (Keyboard.isKeyDown(Keyboard.KEY_A)) { 
      x -= Delta() * speed; 
     } 
     if (Keyboard.isKeyDown(Keyboard.KEY_S)) { 
      y += Delta() * speed; 
     } 
     if (Keyboard.isKeyDown(Keyboard.KEY_D)) { 
      x += Delta() * speed; 
     } 
    } 
} 

設我知道你是否需要查看更多的代碼,謝謝你的時間。

+1

你在調試器中通過了這段代碼嗎? – 2014-09-29 20:36:44

+2

只是三個小的註釋:'if(t.getType()。getPassable()== false)'用這個代替'if(!t.getType()。getPassable())'。 'Math.abs(5)'...和'5'不一樣嗎?最後一個:不要這樣做:'collision = true;'。您正在檢測碰撞並將其保存到變量中。然後你繼續迭代你的循環,如果其他的tile不與玩家碰撞,變量'collision'將被'false'覆蓋。如果你檢測到一個碰撞,那麼'返回true;'而不是。 – Tom 2014-09-29 20:43:17

+0

是的,我不記得我在'Math.abs(5)'中做了什麼,但是我原來的設置爲1,所以如果不能通過的瓦片是上面的一個像素,它會返回true,但我擔心玩家如果'Delta()'太高,精靈可能會跳過它。 – 2014-09-30 01:38:46

回答

1

修正:

public static boolean collisionAbovePlayer(TileGrid grid, float x, float y, int width, int height) { 

    for (Tile[] row : grid.map) { 
     for (Tile t : row) { 

      // Each Tile t in map: 

      if (!t.getType().getPassable()) { 

       // Each impassable tile: 

       if ((x - t.getX() > 0 && x - t.getX() < t.getWidth()) || (x - t.getX() < 0 && Math.abs(x - t.getX()) < width)) { 

        // Tile is within collision x range 

        System.out.println("IN X RANGE"); 

        if (Math.abs((t.getY() + t.getHeight() + 1) - y) < 2) { 
         return true; 
        } 

       } 
      } 
     } 
    } 

    return false; 
} 

在原來的代碼僅返回的最後一張牌是設置「布爾碰撞」爲真,和最後陳述檢查y必需Math.abs()周圍的第一個值。