我有一个指南针,它返回0-360到指南针初始值的起始位置(度)之间的角度,以及一个阈值。
degrees = 0-360
initialDegrees = null
threshold = 20
我有这张支票:
if(degrees > initialDegrees+threshold || initialDegrees == null) { // this is to start the checking
foo();
initialDegrees = degrees
}
用于检查度数是否已经超过阈值进行了正变化(例如,我将指南针向右移动)
但是我如何检查它是否已沿相反方向移动(负变化超出阈值,即我将指南针向左移动)。
if(degrees > initialDegrees-thredshold) // this is always true, and doesn't do what i want
有没有办法做到这一点? 希望您理解我正在努力实现的目标。
答案 0 :(得分:3)
我会看一下区别。
int delta = degrees - initialDegrees;
if (delta > 180)
delta -= 360; // its a negative move.
if (delta < -180)
delra += 360; // actually positive.
if (Math.abs(delta) > threshold)
// meaningful move.
您可以使用数学运算来避免使用if
语句
delta = (delta + 360 + 180) % 360 - 180; // all values between -180 and 179.
或
delta = (delta + 360 + 179) % 360 - 179; // all values between -179 and 180.
答案 1 :(得分:2)
您需要的是shortestAngle
函数。一些数学库已经有了它,但是您可以编写自己的数学库。给定2个角度,您需要找到最小的角度(绝对值),以使第一个角度加上该结果等于第二个角度:
public static float shortestAngle(float from, float to) {
float difference = to - from; //step 1: do flat difference
difference %= 360; //step 2: do module 360 to normalize to (-360, 360) range
if(difference < 0) {
difference += 360; //step3: normalize to [0, 360) range
}
if(difference > 180) {
difference -= 360; //step 4: normalize to (-180, 180] range
}
return difference;
}
之后,您只需比较最短角度是大于阈值还是小于负阈值。