[英]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.