2012-01-14 138 views
0

我一直在寫一個遊戲引擎,我的演員類有問題。我想確定一個矩形(上圖)和矩形的一邊的碰撞。我爲他們寫了兩種方法。Java遊戲碰撞檢測,(側面碰撞)與矩形

public boolean isLeftCollision(Actor actor) { 
    boolean bool = false; 
    Rectangle LeftBounds = new Rectangle(x, y, x-velocity, image.getHeight(null)); 
    bool = LeftBounds.intersects(actor.getBounds()); 
    return bool; 
} 

public boolean isRightCollision(Actor actor) { 
    boolean bool = false; 
    Rectangle RightBounds = new Rectangle(x+image.getWidth(null), y, image.getWidth(null)+velocity, image.getHeight(null)); 
    bool = RightBounds.intersects(actor.getBounds()); 
    return bool; 
} 

這裏速度是下一步的運動。

但他們都給我錯誤(即錯誤的判斷)。我該如何在演員課上解決這個問題。

+0

添加錯誤日誌 – 2012-01-15 00:06:08

+0

@stas如何添加錯誤日誌 – 2012-01-15 00:13:15

+0

lol。運行該程序並複製並粘貼該錯誤。 – 2012-01-15 00:15:57

回答

1

我承認我幾乎無法讀取您的代碼,如果我的回答沒有幫助,我很抱歉。我的猜測是碰撞中的速度會產生錯誤。根據您檢查的頻率以及速度保持的值,您可能會記錄尚未發生的碰撞...

我會在兩個步驟中執行碰撞檢測。

  1. 試驗碰撞
  2. 確定它是高於或一側。

這裏的一些僞代碼:

Rectangle self_shape=this.getBounds(); 
Rectangle other_shape=actor.getBounds(); 
bool collision = self_shape.intersects(other_shape); 
if(collision){ 
    //create two new variables self_centerx and self_centery 
    //and two new variables other_centerx and other_centery 
    //let them point to the coordinates of the center of the 
    //corresponding rectangle 

    bool left=self_centerx - other_centerx<0 
    bool up=self_centery - other_centery<0 
} 

這樣,你可以看看在其他演員相對於定位到你。如果它在上面或一邊。

+0

感謝您的回答,它工作 – 2012-01-15 00:30:09

1

請記住,矩形的第三個參數是寬度,而不是另一邊的x。所以,你真正需要的可能是這樣的:

public boolean isLeftCollision(Actor actor) { 
    return new Rectangle(x - velocity, y, velocity, image.getHeight(null)) 
     .intersects(actor.getBounds()); 
} 

public boolean isRightCollision(Actor actor) { 
    return new Rectangle(x + image.getWidth(null), y, velocity, image.getHeight(null)) 
     .intersects(actor.getBounds()); 
} 

(假設速度是(正)距離向左或向右移動,只有方法要移動的方向將被稱爲)