我寫一個程序,允許用戶左鍵單擊面板,並添加一個反彈球,並用鼠標右鍵單擊要刪除一個球。球以不變的速度從所有的牆壁彈出。我完成了所有這些。我想不出的最後一部分是處理與其他彈跳球的碰撞。應該發生與從牆壁反彈相同的結果。任何幫助將不勝感激。下面是球至今的移動代碼...彈跳球的碰撞
@SuppressWarnings("AccessingNonPublicFieldOfAnotherObject")
private void processMovement(long interval)
{
/* Compute the distance moved in the interval. Decompose the distance
moved into x and y components, and determine the next position of the Ball
by those amounts. */
float x = position.x + velocity.getDistanceX(interval);
float y = position.y + velocity.getDistanceY(interval);
position.setLocation(x, y);
/* Collisions with the walls. If so, adjust the speed and direction for
the next period. */
/* Collision with the east or west (vertical) wall. */
float wall;
if(x <= (wall = 0.0F) ||
x >= (wall = model.getDimension().width - SIZE))
{
x = wall;
velocity.reverseX();
}
/* Collision with the north or south (horizontal) wall. */
if(y <= (wall = 0.0F) ||
y >= (wall = model.getDimension().height - SIZE))
{
y = wall;
velocity.reverseY();
}
position.setLocation(x, y);
}
你嘗試過這麼遠嗎?爲什麼它不工作?這是作業還是課程作業? – Bobulous 2015-04-04 23:02:08
您需要一個集合來存儲每個球對象。然後你需要檢查他們對方的位置,看看是否發生了碰撞。 quradtree結構是一個有效的解決方案 – 2015-04-04 23:35:39