我得到了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);
我得到了角度和距离,但不知道如何让它直接移动。请帮帮我!谢谢!
发布于 2012-02-18 10:48:45
也许用这个会有帮助
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);
}
现在,您有了线上的点的坐标。根据您的需要选择步长到足够小。
发布于 2012-02-18 10:53:50
要从给定角度计算速度,请使用以下命令:
velx=(float)Math.cos((angle)*0.0174532925f)*speed;
vely=(float)Math.sin((angle)*0.0174532925f)*speed;
*speed=your速度:) (玩玩数字看看哪个是正确的)
发布于 2012-02-18 11:07:54
我建议您独立计算运动的x和y分量。使用三角运算会显著降低程序的运行速度。
您的问题的一个简单解决方案是:
float dx = targetX - positionX;
float dy = targetY - positionY;
positionX = positionX + dx;
positionY = positionY + dy;
在此代码示例中,您将计算从您的位置到目标的x和y距离,并在一步中移动到目标位置。
您可以应用时间因子(<1)并多次执行计算,以使对象看起来正在移动。
注意,+和-比cos()
、sin()
等要快得多。
https://stackoverflow.com/questions/9340483
复制