我正在编写一个游戏,但我来到了一个非常困难的地方。基本上我有一个圆圈,我在这个圆圈上有两个角度。角度1(A)是我想要角度2(B)的点。在我的游戏中,我需要检查每一帧是否增加或减少我的角度值一定量(速度)以最终达到第一个角度。我的问题是我该怎么做?
我尝试过这样做,但我似乎没有做对。
bool increase = false;
float B = [self radiansToDegrees:tankAngle];
float A = [self radiansToDegrees:tankDestinationAngle];
float newAngle = B;
if(B < A) {
float C = B - (360 - A);
float D = A - B;
if(C < D) increase = false;
else increase = true;
} else if(B > A) {
float C = B - A;
float D = A - (360 - B);
if(C < D) increase = false;
else increase = true;
}
if(increase) {
newAngle += 1.0;
} else {
newAngle -= 1.0;
}
if(newAngle > 360.0) {
newAngle = 0 + (newAngle - 360.0);
} else if(newAngle < 0.0) {
newAngle = 360 + newAngle;
}
if(newAngle == 0) newAngle = 360;
newAngle = [self degreesToRadians:newAngle];
[self setTanksProperPositionRotation:newAngle];
我想要达到的基本效果是当用户创建一个新点时,角度为1,角度2将朝着角度1移动,选择最快的方向。我想我已经花了大约4个小时试图解决这个问题。
答案 0 :(得分:1)
将0到360度之间的角度标准化,取较小的值:
float normalize(float angle)
{
while(angle < 0)
angle += 360;
return angle % 360;
}
//To use...
float angle1 = A - B;
float angle2 = B - A;
if(normalize(angle1) < normalize(angle2))
//Use angle1
else
//Use angle2
答案 1 :(得分:1)
假设当前和期望为正且小于360:
float inc; // abs. distance from current to desired if incrementing
float dec; // abs. distance from current to desired if decrementing
if (current > desired)
{
inc = current + 360.0f - desired; // incrementing would wrap over
dec = current - desired;
}
else
{
inc = desired - current;
dec = current + 360.0f - desired; // decrementing would wrap over
}
// the expressions above are arranged so inc and dec are both +ve
// so just compare them
if (inc < dec)
newAngle = current + step;
else
newAngle = current - step;
答案 2 :(得分:0)