计算角度是否在两个角度之间 [英] Calculating if an angle is between two angles
问题描述
所以我正在做一个小游戏,我在检查一个角色是否可以看到"另一个角色,如果A在B的一定距离内,并且A方向为+/-,则角色A可以看到角色B.面对B的45度角.
So I am making a little game where I am checking if a character can "see" another where character A can see character B if A is within a certain distance of B, and the direction in degrees of A is +/- 45 degrees of the angle B is facing.
目前,我正在做一些计算,以检查
Currently, I do a little calculation where I'm checking if
(facingAngle - 45) =< angleOfTarget =< (facingAngle + 45)
这很好,除非我们越过360度线.
This works fine except for when we cross the 360 degree line.
比方说facingAngle = 359, angleOfTarget = 5
.在这种情况下,目标偏离中心仅6度,因此我希望函数返回true.不幸的是,5不在314和404之间.
Let's say facingAngle = 359, angleOfTarget = 5
. In this situation, the target is only 6 degrees off center, so I want my function to return true. Unfortunately, 5 is not between 314 and 404.
推荐答案
只需尝试
anglediff = (facingAngle - angleOfTarget + 180 + 360) % 360 - 180
if (anglediff <= 45 && anglediff>=-45) ....
原因是尽管由于包裹效应,角度差异仍为facingAngle - angleOfTarget
,可能会相差360度.
The reason is that the difference in angles is facingAngle - angleOfTarget
although due to wrapping effects, might be off by 360 degrees.
相加180 + 360,然后对360取模,然后相减180,实际上只是将所有内容转换为-180至180度(通过相加或相减360度).
The add 180+360 then modulo 360 then subtract 180, effectively just converts everything to the range -180 to 180 degrees (by adding or subtracting 360 degrees).
然后,您可以轻松地检查角度差,它是否在-45到45度之间.
Then you can check the angle difference easily, whether it is within -45 to 45 degrees.
这篇关于计算角度是否在两个角度之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!