我想从头开始,以确保我理解您的要求。
所以对于
approach()
函数参数“current”表示当前角度。参数“goal”表示所需的角度。参数“delta”表示角度必须达到“目标”的时间(假设秒)。
现在,要计算到该角度的最短路径,您可以简单地执行以下操作:
if(current + (360 - goal) <= 180) // If goal is 180° away it will rotate to the right automatically.
// ... Rotate to the right
else
// ... Rotate to the left
我们可以测试它是否真的有效,因为如果我们采用您要求的值(当前 = 45,目标 = 315)并执行上面的计算,我们应该向右转。
45 + (360 - 315) <= 180
45 + 45 <= 180
90 <= 180, true.
We turn it right.
现在只需根据 delta 计算旋转量。这个相当简单。
我将“totalAngle”声明为一个变量,以跟踪当前角度和目标角度之间的差异。我将在 if/else 代码块中分配这个变量。我还将声明一个布尔值来帮助我跟踪需要旋转的方向。
boolean rotateRight;
float totalAngle;
if(current + (360 - goal) <= 180) {
totalAngle = current + (360 - goal);
rotateRight = true;
}
else {
totalAngle = goal - current;
rotateRight = false;
}
现在假设它每秒旋转一次,我将取 totalAngle 并将其除以传递的秒数(也称为“delta”参数)。然后我修改“current”参数,并返回它。
current -= rotateRight ? (totalAngle / delta) : -(total / delta);
结束函数应该是这样的:
public static float approach(float current, float goal, float delta) {
boolean rotateRight;
float totalAngle;
if(current + (360 - goal) <= 180) {
totalAngle = current + (360 - goal);
rotateRight = true;
}
else {
totalAngle = goal - current;
rotateRight = false;
}
current -= rotateRight ? (totalAngle / delta) : -(totalAngle / delta);
return current;
}
编辑:如果最短路径实际上是最长的,假设“当前 - (360 - 目标)