Latest Uploads
Rpg Potion Sprites

Pakz

Super Shap ... ration Kit

Andy_A

Platdude Spotting

Jayenkai

Nom nom nom

Jayenkai

Rainbow Trout

Pakz

King Salmon

Pakz

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 587|0 -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=- -=+=-
Latest Posts
QOTD : Best TV Show
Jayenkai Mon 09:34
Buy Zelda
rockford Mon 00:55
Repetitive Blogging
rskgames Fri 10:04
TinyBlocks
spinal Fri 06:46
Arduboy Owners Club
spinal Fri 02:30
AGameAWeek : 2017 - Part One
Jayenkai Thu 13:11
A New Korg Gadget!
Jayenkai Thu 12:30
SNES Mini?
rychan Thu 07:11
Steampunk Lamp
Jayenkai Wed 06:05
Finishing Off
rockford Tue 08:20
More

Latest Items
Showcase : Quadoban
rskgames Fri 10:11
Blog : My Arduino experience.
steve_ancell Wed 17:02
Showcase : Roguelike Explorer
Pakz Fri 06:59
Showcase : Infinitron
Jayenkai Mon 07:50
News : Newsletter #311
Jayenkai Thu 17:27
Link : Super Shapes Exploration Kit
Andy_A Thu 11:09
Dev-Diary : Sensitive - Arduboy!
rychan Thu 17:27
Snippet : Skylines
steve_ancell Tue 14:25
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
More

Who's Online
Pakz
Mon, at 10:42
rskgames
Mon, at 10:41
Andy_A
Mon, at 10:28
Jayenkai
Mon, at 09:34
rockford
Mon, at 09:26
steve_ancell
Mon, at 07:10
spinal
Mon, at 06:36
therevillsgames
Mon, at 00:53
Evil Roy Ferguson
Sun, at 19:33
9572AD
Sun, at 16:28
Link to this page
Site : Jayenkai 2006-Infinity | MudChat's origins, BBCode's former life, Image Scaler.