2015-12-03 53 views
0

我正在Java中製作一個Breakout遊戲,並且我已經到了需要能夠檢測到Brick的哪一側與球。目前我正在使用交叉點方法,但是這隻能檢測交叉點,並不具體指明哪一側已被擊中。這是方法(我的一些評論已經添加):如何檢測Java中矩形的哪一側已經命中

public boolean intersects(Rectangle r) { 
    // The width of the Brick as tw 
    int tw = this.width; 
    // The height of the Brick as th 
    int th = this.height; 
    // The width of the given Rectangle as rw 
    int rw = r.width; 
    // The height of the given Rectangle as rh 
    int rh = r.height; 
    // Check if the given Rectangle or Brick does not exist 
    if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) { 

     // If not, then return false because there is nothing to collide/intersect 
     return false; 
    } 

    // The x location of Brick as tx 
    int tx = this.brickLocation.x; 
    // The y location of Brick as ty 
    int ty = this.brickLocation.y; 
    // The x location of the given Rectangle as rx 
    int rx = r.x; 
    // The y location of the given Rectangle as ry 
    int ry = r.y; 

    // RW = RW + RX 
    rw += rx; 
    // RH = RH + RY 
    rh += ry; 
    // TW = TW + TX 
    tw += tx; 
    // TH = TH + TY 
    th += ty; 

    //  overflow || intersect 
    return ((rw < rx || rw > tx) && 
      (rh < ry || rh > ty) && 
      (tw < tx || tw > rx) && 
      (th < ty || th > ry)); 
} 

而且我現在已經把這個方法到我的課之一,我自定義它,但是我無法使它如此它可以檢測到哪一邊已經被擊中,因爲最終的返回語句是如此相互連接的,所以你不能只採用其中的一條線,因爲爲了知道哪一邊結束了,需要知道其他邊,這就是它在這裏做了什麼,如果它已經與所有的邊相交(並且對邊的延伸沒有限制 - 儘管它們當然顯然是有限的),那麼它返回真,如果不是則不是,它沒有觸及因爲否則它會哈已經完成。

我想要做的就是讓這樣做,以便有如果語句決定什麼樣的int返回(我會改變它的返回類型從布爾到int),從而它已經擊中哪一方以便它可以以適當的方式反彈。但由於這些都是相互依賴我不知道如何將它們分開:

//  overflow || intersect 
    return ((rw < rx || rw > tx) && 
      (rh < ry || rh > ty) && 
      (tw < tx || tw > rx) && 
      (th < ty || th > ry)); 

我在這裏看到很多類似的問題,但無論他們是在不同的語言,沒有任何答案,或者沒有回答問題並被接受的答案。所以我想知道是否有人可以告訴我如何區分這些東西,以便它可以檢測到哪一方已經被擊中,因爲我沒有想法?
或者也許有一個Java方法已經可以爲我做到這一點,我不必覆蓋已經存在的一個?我有Oracle JDK 8的最新版本。

+0

我認爲你應該畫一個圖並標記哪些座標是什麼;這應該有助於你理解那些「相互關聯」的陳述究竟是什麼。哦,用其他答案寫在哪種語言並不重要 - 數學總是數學。 –

+0

如果您通過向其座標添加偏移量來「移動」球,使用更大的偏移量以獲得更高的速度,則必須準備好在沒有任何時間框架內相交的情況下擊中邊緣。更糟糕的是,你可以用非常快速的球運動相交相反的邊緣。計算邊交點在這裏是錯誤的方法。 – Holger

回答

0

嘗試讓您的相交(Rectangle r)函數在沒有碰到任何邊的情況下返回-1,並且0-1-2-3確定您碰到的邊。根據的哪一部分已經增加..你可以做到這一點

1

一種方式轉移球時,我假設你做這樣的事情:

ball.x += speedX; 
ball.y += speedY; 

你可以反過來說,這樣的:

ball.x += speedX; 
if (intersects(ball, brick)) 
{ 
    //Ball touched brick on left/right side (depending if speedX is positive or negative) 
} 
ball.y += speedY; 
if (intersects(ball, brick)) 
{ 
    //Ball touched brick on top/bottom side (depending if speedY is positive or negative) 
} 
+0

如果你走這條路線,你可能可能有'intersects'取另一個參數來指示檢查左/右或上/下。這樣你就不會在兩個部分都進行檢查。 – gonzo

+0

@gonzo雖然我同意,但有一些方法可以避免兩次調用'intersects()',你的方式聽起來不對。如果它只檢查左/右,在第一次調用中,當球在磚塊上方時,它可能會返回true。只要它有效,OP就可以根據需要優化它。 – TomTsagk