[英]Moving directly from Point A to Point B
I got x and y (My position) and also destination.x and destination.y (where I want to get). 我得到了x和y(我的位置),还有destination.x和destination.y(我想获得的位置)。 This is not for homework, just for training. 这不是为了功课,只是为了训练。
So what I did already is 所以我已经做的是
float x3 = x - destination.x;
float y3 = y - destination.y;
float angle = (float) Math.atan2(y3, x3);
float distance = (float) Math.hypot(x3, y3);
I got angle and distance but don't know how to make it move directly. 我有角度和距离,但不知道如何使其直接移动。 Please help! 请帮忙! Thanks! 谢谢!
Maybe using this will help 也许使用它会有所帮助
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);
}
Now you have the coordinates of the points on the line. 现在,您有了直线上点的坐标。 Choose step to small enough according to your need. 根据需要选择足够小的步骤。
To calculate the velocity from a given angle use this: 要从给定角度计算速度,请使用以下命令:
velx=(float)Math.cos((angle)*0.0174532925f)*speed;
vely=(float)Math.sin((angle)*0.0174532925f)*speed;
*speed=your speed :) (play with the number to see what is the right) *速度=你的速度:)(玩数字看看什么是正确的)
I recommend calculating the x and y components of your movement independently. 我建议您独立计算机芯的x和y分量。 using trigonometric operations slows your program down significantly. 使用三角运算会显着降低程序速度。
a simple solution for your problem would be: 解决您问题的简单方法是:
float dx = targetX - positionX;
float dy = targetY - positionY;
positionX = positionX + dx;
positionY = positionY + dy;
in this code example, you calculate the x and y distance from your position to your target and you move there in one step. 在此代码示例中,您计算了从位置到目标的x和y距离,然后一步步移动到该位置。
you can apply a time factor (<1) and do the calculation multiple times, to make it look like your object is moving. 您可以应用时间因子(<1)并多次执行计算,使其看起来像您的对象正在移动。
Note that + and - are much faster than cos()
, sin()
etc. 注意+和 - 比cos()
, sin()
等快得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.