我正在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的最新版本。
我認爲你應該畫一個圖並標記哪些座標是什麼;這應該有助於你理解那些「相互關聯」的陳述究竟是什麼。哦,用其他答案寫在哪種語言並不重要 - 數學總是數學。 –
如果您通過向其座標添加偏移量來「移動」球,使用更大的偏移量以獲得更高的速度,則必須準備好在沒有任何時間框架內相交的情況下擊中邊緣。更糟糕的是,你可以用非常快速的球運動相交相反的邊緣。計算邊交點在這裏是錯誤的方法。 – Holger