我正在研究一個程序,它模擬在一個字段中移動的對象。該領域具有1024x1024的界限。該對象不能在x,y座標下低於0,並且它不能超過1024.我爲每個對象創建一個名爲「move()」的方法,以當前速度將對象移動到當前方向。如果物體接近邊界,它會以新的方向和相同的速度轉向。移動的物體卡在角落
我遇到的問題是,當我的一個對象接近x和y邊界(字段的角落)時,它會卡在角落裏。就好像它試圖遠離角落,但隨後又轉回來。它必須喜歡那個角落。我查看了我的代碼和我,我的邏輯似乎是正確的。我檢查以確保新的方向不是負的或超過359.我檢查以確保新的x,y與新方向的座標也在範圍內。我甚至有辦法設定一個新的方向。
我試過用不同的邏輯重新實現這個方法,但沒有運氣。如果有人可能在我的編程中發現缺陷或指出可能導致它的原因,那麼將非常感激。
我試圖調試並逐步通過我的程序,我發現當它到達角落時,它會改變方向轉向,移動大約3個空格,然後回到角落。必須是一個美妙的角落。
代碼移動方法如下:
public void move(){
localX = super.getX();
localY = super.getY();
float newX=0, newY=0;
float testX, testY;
boolean acceptX = false, acceptY = false;
testX = (float) (Math.cos(direction)*10) + localX;
testY = (float) (Math.sin(direction)*10) + localY;
int testDirection;
while(!acceptX){
if(testX >= 0 && testX <= bound){
newX = testX;
acceptX = true;
}//end if statement
else{
if(direction+180 > 359){
setDirection(direction-180);
testX = (float) (Math.cos(Math.toRadians(direction))*speed) + localX;
}
else{
setDirection(direction+180);
testX = (float) (Math.cos(Math.toRadians(direction))*speed) + localX;
}
}//end else
}//end while that checks for X value
while(!acceptY){
if(testY >= 0 && testY <= bound){
newY = testY;
acceptY = true;
}//end if statement
else{
if(direction+180 > 359){
setDirection(direction-180);
testY = (float) (Math.sin(Math.toRadians(direction))*speed) + localY;
}
else{
setDirection(direction+180);
testY = (float) (Math.sin(Math.toRadians(direction))*speed) + localY;
}
}//end else
}//end while that checks for Y value
super.setX(newX);
super.setY(newY);
}
這裏是setDirection代碼
public void setDirection(int d) {
direction = d;
}
我們還需要設置'direction'的代碼。可能它出於某種原因偏向於朝着角落移動。 – Donnie 2010-11-12 00:50:54
沒問題,上面加了。 – Seephor 2010-11-12 00:54:08
setDirection((direction + 180)%360)。擺脫那些如果。 – 2010-11-12 00:54:54