簡體   English   中英

直接從A點移動到B點

[英]Moving directly from Point A to Point B

我得到了x和y(我的位置),還有destination.x和destination.y(我想獲得的位置)。 這不是為了功課,只是為了訓練。

所以我已經做的是

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

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

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

也許使用它會有所幫助

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);
}

現在,您有了直線上點的坐標。 根據需要選擇足夠小的步驟。

要從給定角度計算速度,請使用以下命令:

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

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

我建議您獨立計算機芯的x和y分量。 使用三角運算會顯着降低程序速度。

解決您問題的簡單方法是:

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

positionX = positionX + dx;
positionY = positionY + dy;

在此代碼示例中,您計算​​了從位置到目標的x和y距離,然后一步步移動到該位置。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM