Latest Uploads
Platdude Spotting

Jayenkai

Nom nom nom

Jayenkai

Rainbow Trout

Pakz

King Salmon

Pakz

Snooker

Jayenkai

You've ... o have you

Jayenkai

Articles + Tutorials > Advanced Techniques ( Created 18 September 2013 | Last Edited 08 January 2017)

Maths 101 - Episode 1: Basic Trigonometry by shroom_monk | No Votes
A coding oriented introduction to trigonometry.
For general use
In this article, we'll look at some trigonometry, all from scratch. Never encountered trig before? No problem! However, once we've covered the basics, we'll take a look at some common coding applications, rather than delving too deeply into the theory.

Before we start...

The core part of this subject is the use of the trigonometric functions. A function is a mathematical object that takes one or more values, does something with them, and returns another value; these are of course analogous to functions in programming!

Some of the trigonometric functions we will be using take angles as a parameter, but depending on the language you are using, your functions may expect values in degrees or radians. If you're unfamiliar with radians, take a look here before continuing. Make sure you know which units your language uses, or you'll get weird results!

For simplicity, unless otherwise noted, we will be using degrees in this tutorial. By convention, 0 degrees is taken to be due east, and increasing the number of degrees moves us anticlockwise.

What is Trigonometry?

Trigonometry, or trig for short (trigonometry is a pain to have to keep typing!), is a branch of mathematics related to some properties of triangles, but that then extends out much further. For our purposes, we shall consider a right-angled triangle, and one of its angles that isn't the right-angle.



The angle we are considering is theta (θ). The longest side in the triangle is the hypotenuse, labelled H. Note that this is always 'opposite' the right-angle - i.e. the right-angle does not touch it. The side opposite theta is labelled O for opposite, and the other side is labelled A for adjacent. We shall be referring to this triangle from now on.

Sine, Cosine and Tangent

As mentioned, we will be using trig functions. You will need a calculator if you want to use them - except for a handful of specific values, you can't really calculate their outputs in your head.

Sine, cosine and tangent, usually written as sin, cos and tan, are the three most common trig functions. Each of them takes an angle and returns a ratio, and their behaviours are closely linked to our triangle above. If we take the sin, cos and tan of our angle theta, we find that:
sin(theta) = O / H
cos(theta) = A / H
tan(theta) = O / A

If you think about it, you will realise that sin and cos can only ever output values between -1 and 1 (the hypotenuse is always longer than each of the opposite and adjacent sides), and that tan(90), tan(270), etc cannot be evaluated (try to draw that triangle!). You will also need to accept the 'existence' of triangles with sides of negative or zero length to see how the full range of angles can be covered by these functions.

Rather than draw my own, here are what these functions look like when plotted, nicked from another site:
Highslide JS

(For the sake of completeness, there are three other similar trig functions...
cosec(theta) = H / O
sec(theta) = H / A
cotan(theta) = A / O
but these are just flipped versions of sin, cos and tan, so they are rarely used, and we won't be using them at all.)

To remember which trig function is which, there is the good old mnemonic SOHCAHTOA:
Sin Opposite Hypotenuse
Cos Adjacent Hypotenuse
Tan Opposite Adjacent

Inverse Functions

Just as square has square root, the trig functions have inverses with which to 'undo' them. These are arcsin, arccos and arctan (also written with superscript '-1's to denote inverse, although I can't do superscripts here for some reason).

Since these are the inverses, whereas sin, cos and tan take an angle and give a ratio, arcsin, arccos and arctan take a ratio and give an angle. Also, of course, as inverses, arcsin(sin(x)) = x, arccos(cos(x)) = x, and arctan(tan(x)) = x (except when tan(x) is undefined).

What can we do with them?

If you were being taught this for the first time in maths, you'd now go on to use these functions to take triangles that you know some information about, and calculate what the remaining unknown values are. However, this, alongside further conclusions of trigonometry such as the sine and cosine rules, doesn't have a great deal of application to programming, particularly of games, so now we shall consider some common things you might use trig for.

Full Movement in 2D

Say you have a character in a top-down 2D world, and you want that character to move at 1 unit per second. If they just move up, down, left or right, that's easy - just add or subtract 1 from their x or y position, depending what was pressed. But what if they try to move down and right at the same time? If you add 1 to both the x and y coordinates, then the character will actually have moved more than 1 unit! Using Pythagoras' Theorem, we see they would in fact move sqrt(1*1 + 1*1) = sqrt(2), or about 1.41 units. How do we resolve this?

Consider our triangle from before. If our character wants to move by r units from their current position through theta degrees from 0 degrees, that gives us some value of theta and a hypotenuse of r. Looking at the definitions of our trig functions, we see that:
sin(theta) = y / r
cos(theta) = x / r
...so:
x = r * cos(theta)
y = r * sin(theta)



i.e. To move our character by r units at theta degrees, add r * cos(theta) to their x position and r * sin(theta) to their y position. In this way, more realistic motion can be achieved - for instance, if you were making an Asteroids clone, this is how you would move the spaceship, the asteroids, and the bullets.

Calculating Angles

Now let's consider the reverse situation. Say our character has a gun, and can aim at where the mouse is pointing. Once we know what angle the bullet is going at, we can use our previous work to make it travel; but how do we know what that angle is?

Let's look at our old triangle again. We know the x and y distances from the character to the target, and we want to find theta.



From our trig function definitions, we have:
tan(theta) = y / x

So, using the inverse function:
arctan(tan(theta)) = arctan(y / x)
theta = arctan(y / x)

Unfortunately, it is not that simple. The equation will fail if x = 0, since we can't divide by 0, and our process doesn't hold if theta was equal to 90, 270, etc, since tan doesn't evaluate for those values. Additionally, since the tan graph repeats itself every 180 degrees, we can't get an angle within the full 0-360 degree range.

Fortunately, most programming languages implement a function called atan2. This function takes 2 values: the y value and the x value from our formula, and gives you the angle that you want, by taking special consideration of the whether the values are positive or negative, and if x is 0. Note that usually the y value is given before the x value - this is because in the original formula, y also comes first.

So, to calculate the angle we are aiming at, we would typically use something like:
theta = atan2(aimY - charY, aimX - charX)

Summary

  • The trig functions are sin, cos and tan.
  • Remember how they are defined with SOHCAHTOA.
  • Their inverses are arcsin, arccos and arctan.
  • To move by r units in a direction of theta degrees, add r * cos(theta) to x and r * sin(theta) to y.
  • To calculate the angle to something, use atan2(yDif, xDif).

Trigonometry goes a lot deeper, but unless you're doing something more geometric, you probably won't need much more than this. Next time, we'll change tack and look at vectors.

Latest Comments

Posted : Saturday, 07 January 2017, 21:49
Pakz


What is a theta?

There is a dead link in there.

Homepage : http://cromdesi.home.xs4all.nl/
Posted : Sunday, 08 January 2017, 14:07
shroom_monk


'Theta' is the Greek letter θ. We often use Greek letters in maths for variable names, and θ is often used to refer to an angle. Of course, we could just have easily called it t, or a, or anything else we liked!

Since we can't use Greek letters as variable names in program code, though, I have written it as 'theta' throughout this article.

(I have also gone and fixed the image in the article.)

-=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- (c) WidthPadding Industries 1987 599|0 -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=-
Latest Posts
Laptop Aaargh...
Jayenkai Fri 17:32
GamerBlock
rockford Fri 16:51
A New Korg Gadget!
Jayenkai Fri 16:35
Happy Birthday, Spinal
Jayenkai Fri 08:40
Watch Switch - Fitbit Blaze
rockford Fri 03:52
London Car/Stab Incident
Jayenkai Thu 13:36
Happy Birthday Evil Roy Ferguson
rockford Wed 16:21
Spinal's Return to Android
Jayenkai Tue 13:41
AGameAWeek : 2017 - Part One
Jayenkai Tue 08:10
Poll : Cooking
Jayenkai Mon 05:11
More

Latest Items
Blog : My Arduino experience.
steve_ancell Fri 13:45
Snippet : Skylines
spinal Fri 06:13
Showcase : Infinitron
rychan Tue 03:02
Dev-Diary : PS2 to N64 Adapter
spinal Sun 10:49
Link : Vector Tutorials/Help page.
Pakz Thu 23:00
Blog : mini project
spinal Sun 10:13
Showcase : Blockman Returns
Jayenkai Fri 03:04
Snippet : Wall Tracing on Random Maps (rpg)
rskgames Wed 22:48
Snippet : Path Following
Pakz Mon 16:25
Snippet : Flowers (Jan 2017)
Kuron Thu 01:13
Showcase : Clusters of Hex
therevillsgames Mon 15:01
Article : Maths 101 - Episode 1: Basic Trigonometry
shroom_monk Sun 14:07
Article : Maths 101 - Episode 5: Line Intersection
shroom_monk Sun 14:02
Dev-Diary : Normals and Dot products
Pakz Sat 20:37
Pets : Molly On The Couch
Jayenkai Thu 04:32
More

Who's Online
rskgames
Fri, at 23:01
therevillsgames
Fri, at 21:13
9572AD
Fri, at 18:07
steve_ancell
Fri, at 18:03
Jayenkai
Fri, at 17:53
rockford
Fri, at 16:55
Krakatomato
Fri, at 15:38
spinal
Fri, at 15:28
Pakz
Fri, at 14:13
shroom_monk
Fri, at 13:09
Link to this page
Site : Jayenkai 2006-Infinity | MudChat's origins, BBCode's former life, Image Scaler.