Trigonometry for Game Programming – SpriteKit and Swift Tutorial: Part 1/2

Learn trigonometry for game programming using SpriteKit and Swift. You will learn the theory and then practice using trigonometry by making a space shooter game! By Bill Morefield.

Leave a rating/review
Download materials
Save for later
Share

Contents

Hide contents

Trigonometry for Game Programming – SpriteKit and Swift Tutorial: Part 1/2

40 mins

Update note: Bill Morefield updated this tutorial for Xcode 9.3, Swift 4.1, and iOS 11. Matthijs Hollemans wrote the original tutorial.

A common misconception is that game programmers need to know a lot about math. Although calculating distances and angles does require math, it’s actually quite easy after understanding a few fundamental concepts.

In this tutorial, you’ll learn about some important trigonometric functions and how you can use them in your games. Then you’ll get some practice applying these theories by developing a simple space shooter iOS game using the SpriteKit framework.

Don’t worry if you’ve never used SpriteKit before or you plan on using a different framework for your game — the mathematics covered in this tutorial are applicable to any game engine you might choose to use.

Note: The game you’ll build in this tutorial uses the accelerometer so you’ll need an iOS device and a developer account.

Getting Started

Trigonometry. It sounds like a mouthful, but trigonometry (or trig, for short) simply means calculations with triangles (that’s where the tri comes from).

You may not have realized this, but games are full of triangles. For example, imagine you have a spaceship game and you want to calculate the distance between these two ships:

Distance between ships

You have the X and Y position of each ship, but how can you find the length of the diagonal white line?

Well, you can simply draw a line between each ship’s center point to form a triangle like this:

Note that one of the corners of this triangle has an angle of 90 degrees. This is known as a right triangle and the triangle type that you’ll be dealing with in this tutorial.

Any time you can express something in your game as a triangle with a 90-degree right angle — such as the spatial relationship between the two sprites in the picture — you can use trigonometric functions to do calculations on them.

For example, in this spaceship game, you might want to:

  • Have one ship shoot a laser in the direction of the other ship
  • Have one ship start moving in the direction of another ship to chase
  • Play a warning sound effect if an enemy ship is getting too close

All of this, and more, you can do with the trigonometry power!

Your Arsenal of Functions

First, let’s get the theory out of the way. Don’t worry, I’ll keep it short so you can get to the fun coding bits as quickly as possible.

These are the parts that make up a right triangle:

In the picture above, the diagonal side is called the hypotenuse. It always sits across the right angle and is the longest of the three sides.

The two remaining sides are called the adjacent and the opposite when seen from the triangle’s bottom-left corner.

If you look at the triangle from the top-right corner, then the adjacent and opposite sides switch places:

Alpha (α) and beta (β) are the names of the two other angles. You can call these angles anything you want (as long as it sounds Greek!), but usually alpha is the angle in the corner of interest and beta is the angle in the opposing corner. In other words, you label your opposite and adjacent sides with respect to alpha.

The cool thing is that if you only know a total of two elements (combination of sides and non-right angles), trigonometry allows you to find out all the remaining sides and angles using the trigonometric functions sine, cosine and tangent. For example, if you know any angle and the length of one of the sides, then you can easily derive the lengths and angles of the other sides and corners:

You can see the sine, cosine, and tangent functions (often shortened to sin, cos and tan) are just ratios. Again, if you know the alpha and the length of one of the sides, then sin, cos and tan are ratios that relate two sides and the angle together.

Think of the sin, cos and tan functions as “black boxes” – you plug in numbers and get back results. They are standard library functions, available in almost every programming language including Swift.

Note: The behavior of the trigonometric functions can be explained in terms of projecting circles onto straight lines, but you don’t need to know how to derive those functions in order to use them. If you’re curious, there are plenty of sites and videos to explain the details; check out the Math is Fun site for one example.

Know Angle and Length, Need Sides

Let’s consider an example. Suppose the alpha angle between the ships is 45 degrees and the hypotenuse is 10 points long.

Triangles-in-games-measured

You can then plug these values into the formula:

sin(45) = opposite / 10

To solve this for the hypotenuse, you simply shift this formula around a bit:

opposite = sin(45) * 10

The sine of 45 degrees is 0.707 (rounded to three decimal places), and filling that in the forumla gives you the result:

opposite = 0.707 * 10 = 7.07

Know 2 Sides, Need Angle

The formulas above are useful when you already know an angle, but that is not always the case – sometimes you know the length of the two side and are looking for the angle between them. To derive the angle, you can use the inverse trig functions, also known as arc functions:

Inverse trig functions

  • angle = arcsin(opposite/hypotenuse)
  • angle = arccos(adjacent/hypotenuse)
  • angle = arctan(opposite/adjacent)

If sin(a) = b, then it is also true that arcsin(b) = a. Of these inverse trig functions, you will probably use the arc tangent (arctan) the most in practice because it will help you find the hypotenuse. Sometimes these functions are written as sin-1, cos-1, and tan-1, so don’t let that confuse you.

Know 2 Sides, Need Remaining Side

Sometimes you may know two side lengths and you need to know third side length.

This is where geometry’s Pythagorean Theorem comes to the rescue:

a2 + b2 = c2

Or, put in terms of the triangle sides:

opposite2 + adjacent2 = hypotenuse2

If you know any two sides, calculating the third is simply a matter of filling in the formula and taking the square root. This is a very common thing to do in games and you’ll do it several times in this tutorial.

Note: Want to drill this formula into your head while having a great laugh at the same time? Search YouTube for “Pythagoras song” — it’s an inspiration for many!