Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating if an angle is between two angles

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) 

This works fine except for when we cross the 360 degree line.

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.

like image 371
user1641573 Avatar asked Sep 02 '12 08:09

user1641573


People also ask

How do you tell if an angle is between two angles?

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). Then you can check the angle difference easily, whether it is within -45 to 45 degrees.

What is the formula for angle between two lines?

Formulas for Angle Between Two Lines The angle between two lines, of which one of the line is y = mx + c and the other line is the x-axis, is θ = Tan-1m.


1 Answers

Just try

anglediff = (facingAngle - angleOfTarget + 180 + 360) % 360 - 180  if (anglediff <= 45 && anglediff>=-45) .... 

The reason is that the difference in angles is facingAngle - angleOfTarget although due to wrapping effects, might be off by 360 degrees.

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).

Then you can check the angle difference easily, whether it is within -45 to 45 degrees.

like image 151
ronalchn Avatar answered Oct 06 '22 03:10

ronalchn