Angles Without Trigonometry

I've mentioned before about it being a good idea to avoid using trigonometric functions in games.  There's an interesting article here about some of the reasons for avoiding it with reference to 3D geometry, but since I'm making 2D games at the moment I'm more concerned with how to avoid it in 2D, and I've written a C# struct for Unity to make this easier.

As I said previously, any angle in 2D can be represented by a normalised vector (a vector with a length of 1); the angle the vector represents is how far you would have to turn anticlockwise from a line pointing to the right, so a vector pointing diagonally up and right represents the angle 45 degrees.

Representing a 2D angle this way has a lot of advantages.  Firstly, the x and y components of the vector are the cosine and sine of the angle, so as long as we keep the vector normalised, we can read off these values easily instead of their being computationally expensive operations as they normally would be.  True, it takes a normalisation to get this representation in the first place, but that's still cheaper than three transcendental functions (an atan2 to get the angle, then a sine and cosine).

Then we can often work with the angles and keep them normalised, just by using trigonometric identities. (This is also equivalent to basing 2D angles on complex numbers.)  So adding two angles together or subtracting one from another, and automatically having the sine and cosine of the new angle, only requires a few multiplications and additions. Common operations on angles like rotating by a right angle are also easy, as is converting to a vector (which is essentially what it already is). My equality operator is only accurate to within about a tenth of a degree, but it doesn't need checking for whether angles are a whole rotation apart - the representation is naturally periodic.

I've added whatever other helpful features into the class that I can imagine wanting while working with angles, including the PerpDot operator that Unity's own Vector2 structure leaves out.  I hope you find it useful.

Download Angle2D class

This entry was posted in Unity and tagged , , , , , . Bookmark the permalink.

Comments are closed.