如何选择最短的旋转方向成一个角度 [英] How to get to an angle choosing the shortest rotation direction
问题描述
我的游戏中有一个角色,必须平稳旋转才能达到所需的角度.将angle
设为当前角度,将touchAngle
设为所需角度,该角度始终在0到360之间.我想在每次游戏更新中为当前角度添加+ 1/-1,以达到所需的touchAngle
.问题是首先必须选择方向,并且必须在0到360之间.这是我的伪代码:
I have a character in my game that must rotate smoothly to get to a desired angle. Consider angle
as the current angle and touchAngle
as the desired angle which is always between 0 to 360. I want to add +1/-1 to current angle in every game update to get to the desired touchAngle
. The problem is first it must chose direction and it must be between 0 to 360. this is my pseudo code:
int touchAngle;
float angle;
public void update()
{
if ((int)angle != touchAngle) angle += ???
}
推荐答案
由于您的值始终在[0 360]
间隔中进行规范化,因此这应该不太困难.
您只需要区分两种不同的情况:
Since you have values that are always normalized in the interval [0 360]
this should not be too hard.
You just need to distinguish two different cases:
angle < touchAngle
angle > touchAngle
在第一种情况下,我们想逆时针旋转,因此更新必须为angle =+ 1
(假设您希望在每个更新周期将其设置为1).
在第二种情况下,我们想顺时针旋转,因此更新应为angle -= 1
.
in the first case we want to rotate counterclockwise so the update has to be angle =+ 1
(assuming that you want to turn of 1 every update cycle).
In the second case we want to turn clockwise so the update should be angle -= 1
.
问题在于,这并不总是最短的旋转方式.例如,如果:
The problem is that this is not always the shortest way to rotate. For instance if:
angle == 359
touchAngle == 1
我们不想一直走到358、357、356 ...相反,我们只想逆时针旋转2个单位:360、1.
比较角度abs(angle - touchAngle)
之间的距离即可实现.
we don't want to make all the way 358, 357, 356...instead we want to rotate counterclockwise for just 2 units: 360, 1.
This can be achieved comparing the distance between the angles abs(angle - touchAngle)
.
如果此值大于180
,则表示我们走错了路,所以我们必须这样做.
If this value is bigger than 180
it means we are going the wrong way, so we have to do the way around so
if(angle < touchAngle) {
if(abs(angle - touchAngle)<180)
angle += 1;
else angle -= 1;
}
else {
if(abs(angle - touchAngle)<180)
angle -= 1;
else angle += 1;
}
当然,所有这一切直到((int)angale != touchAngle)
.
我可能在这些案例上犯了错误,但这是原则.
of course all of this until ((int)angale != touchAngle)
.
I might have made mistakes with the cases but this is the principle.
这篇关于如何选择最短的旋转方向成一个角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!