2012-02-18 93 views
1

我得到了x和y(我的位置)以及destination.x和destination.y(我想要的地方)。這不是作業,只是爲了訓練。直接從A點移動到B點

所以我所做的已經是

float x3 = x - destination.x; 
float y3 = y - destination.y; 

float angle = (float) Math.atan2(y3, x3); 
float distance = (float) Math.hypot(x3, y3); 

我的角度和距離,但不知道如何使它直接移動。 請幫忙! 謝謝!

+0

你所說的「直接移到」呢? – 2012-02-18 10:47:50

+0

@OliCharlesworth @OliCharlesworth我的意思是,它從一個點移動到另一個點,但在此之前它計算角度以及它必須走的方向,以便它走向最短路徑。 – IvanDonat 2012-02-18 11:37:36

回答

1

也許用這將有助於

float vx = destination.x - x; 
float vy = destination.y - y; 
for (float t = 0.0; t < 1.0; t+= step) { 
    float next_point_x = x + vx*t; 
    float next_point_y = y + vy*t; 
    System.out.println(next_point_x + ", " + next_point_y); 
} 

現在你已經上線的點的座標。根據您的需要選擇足夠小的步驟。

+0

哇!非常感謝!這真的很棒!我調整了一下代碼,使其更簡單易用(對我來說):D – IvanDonat 2012-02-18 10:58:57

1

從給定的角度計算速度使用:

velx=(float)Math.cos((angle)*0.0174532925f)*speed; 
vely=(float)Math.sin((angle)*0.0174532925f)*speed; 

*速度=你的速度:)(用數字玩,看看什麼是正確的)

1

我建議計算x和你的運動的y個組成部分獨立。使用三角運算的 會顯着減慢程序的速度。

您的問題一個簡單的解決辦法是:

float dx = targetX - positionX; 
float dy = targetY - positionY; 

positionX = positionX + dx; 
positionY = positionY + dy; 
在此代碼示例

,你計算從位置x和y的距離你的目標 你一步到位搬到那裏。

您可以應用時間因子(< 1)並進行多次計算,使其看起來像物體正在移動。

注意+和 - 比cos()快得多,sin()

相關問題