2012-02-18 76 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()

相关问题