Trigonometry for Game Programming [Sprite Kit Version]: Part 1/2

Learn about trigonometry functions like sin, cos, and tan while you make a fun iOS space game! By Tony Dahbura.

Leave a rating/review
Save for later
Share
You are currently viewing page 2 of 7 of this article. Click here to view the first page.

Contents

Hide contents

Trigonometry for Game Programming [Sprite Kit Version]: Part 1/2

70 mins

Know 2 Sides, Need Angle

The above formulas are useful when you already know an angle, but that is not always the case – sometimes it is the angle you are looking for. Then you need to know the lengths of at least two of the sides and plug these into the inverse functions:

Inverse trig functions

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

In other words, if sin(a) = b, then it is also true that arcsin(b) = a. Of these inverse functions, you will use the arc tangent (arctan) the most in practice. Sometimes these functions are also notated as sin-1, cos-1, and tan-1, so don’t let that fool you.

Is any of this sinking in or sounding familiar? Good, but you’re not done yet with the theory lesson – there is still more that you can calculate with triangles.

Know 2 Sides, Need Remaining Side

Sometimes you may know the length of two of the sides and need to know the length of the third, like in the example at the beginning of this tutorial where you wanted to find the distance between the two space ships.

This is where Trigonometry’s Pythagorean Theorem comes to the rescue. Even if you forgot everything else about math, this is probably the one formula you do remember:

a2 + b2 = c2

Or, put in terms of the triangle that you saw earlier:

opposite2 + adjacent2 = hypotenuse2

If you know any two of these sides, then 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 be seeing 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!

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!

Have Angle, Need Other Angle

Lastly, the angles. If you know one of the non-right angles from the triangle, then figuring out the other ones is a piece of cake. In a triangle, all angles always add up to a total of 180 degrees. Because this is a right triangle, you already know that one of the angles is 90 degrees. That leaves:

alpha + beta + 90 = 180

Or simply:

alpha + beta = 90

The remaining two angles must add up to 90 degrees. So if you know alpha, you also know beta, and vice-versa.

And those are all the formulas you need to know! Which one to use in practice depends on the pieces that you already have. Usually you either have the angle and the length of at least one of the sides, or you don’t have the angle but you do have two of the sides.

Enough theory. Let’s put this stuff into practice.

To Skip, or Not to Skip?

In the next few sections, you will be setting up a basic Sprite Kit project with a space ship that can move around the screen using the accelerometer. This won’t involve any trigonometry (yet), so if you already know Sprite Kit and feel like this guy:

"F that!" guy

Then feel free to skip ahead to the Begin the Trigonometry! section below – I have a starter project waiting for you there.

But if you’re the type who likes to code everything from scratch, keep reading! :]

Creating the Project

First make sure you have Xcode 5 or later, since it is the first version of Xcode to include Sprite Kit.

Next start up Xcode, select File\New\Project…, choose iOS\Application\SpriteKit Game template, and click Next:

Select SpriteKit Template

Name the project TrigBlasterSK and set the device family to iPhone. Build and run the template as-is. If all works OK, you should see the following:

HelloWorld

Download the resources for this tutorial. This file contains the images for the sprites and the sound effects. Unzip it and drag the art folder into Xcode to add it to the project. In the import dialog, make sure Copy items into destination group’s folder is checked.

DragArtIntoProject

Import Resources Into Project

Great, the preliminaries are over and done with – now let’s get coding for real.

Steering with Accelerometers

Because this is a simple game, you will be doing all your work inside a single class: the MyScene.m. Right now, this scene contains a bunch of stuff that you don’t need. For starters, it does not start up with the correct orientation so let’s fix that first.

Switching to Landscape Orientation

First, open your target setting by clicking your TrigBlasterSK project in the Project Navigator, selecting the TrigBlasterSK target. Then, in the Deployment Info section make sure General is checked at the top, under Device Oritentation uncheck all but Landscape Right as shown below:

Landscape Settings

If you build and run, the app will launch in Landscape orientation but its graphic context is still not landscape. The details of this are covered in our space game tutorial, but for now you need to have the ViewController.m file changed a bit so the start up code is executed later in the process.

Select the ViewController.m and replace the viewDidLoad method with the following:

- (void)viewDidLoad
{
    [super viewDidLoad];
}

-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    // Configure the view.
    // Configure the view after it has been sized for the correct orientation.
    [self startScene];
}

- (void)startScene
{
    SKView *skView = (SKView *)self.view;
    if (!skView.scene) {
        skView.showsFPS = YES;
        skView.showsNodeCount = YES;
        
        // Create and configure the scene.
        MyScene *theScene = [MyScene sceneWithSize:skView.bounds.size];
        theScene.scaleMode = SKSceneScaleModeAspectFill;
        
        // Present the scene.
        [skView presentScene:theScene];
    }
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

The above code moved the scene creation to the viewWillLayoutSubviews method where the layout orientation is known. There is also an added method at the bottom prefersStatusBarHidden that will cause the status bar to be removed from your game while it is running-giving more realism during play.

Replace the contents of MyScene.m with:

#import "MyScene.h"

@implementation MyScene

-(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]) {
        /* Setup your scene here */
        
        self.backgroundColor = [SKColor colorWithRed:94.0/255.0 green:63.0/255.0 blue:107.0/255.0 alpha:1.0];
    
    }
    return self;
}


-(void)update:(NSTimeInterval)currentTime {
    /* Called before each frame is rendered */
}

@end

Build and run, and you should see nothing but purple:

purple-background

Let’s make things a bit more exciting by adding a spaceship to the scene. You will need some instance variables for this, so modify the @implementation line in MyScene.m as follows:

@implementation MyScene
{
    CGSize _winSize;
    SKSpriteNode *_playerSprite;
}

The _winSize variable stores the dimensions of the screen, which is useful because you will be referring to that quite often. The _playerSprite variable holds the spaceship sprite.

Now change initWithSize to the following:

-(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]) {
        /* Setup your scene here */
        
        self.backgroundColor = [SKColor colorWithRed:94.0/255.0 green:63.0/255.0 blue:107.0/255.0 alpha:1.0];
    
        _winSize = CGSizeMake(size.width, size.height);
        
        _playerSprite = [SKSpriteNode spriteNodeWithImageNamed:@"Player"];
        _playerSprite.position = CGPointMake(_winSize.width - 50.0f, 60.0f);
        [self addChild:_playerSprite];
    }
    return self;
}

This is all pretty basic if you have worked with Sprite Kit before. The player sprite is positioned in the bottom-right corner of the screen. Remember that with Sprite Kit, it is the bottom of the screen that has y-coordinate 0, unlike in UIKit, where y = 0 points to the top of the screen. You have moved the x-coordinate to 60.0 to get it above the status text being shown.

Build and run to try it out, and you should see the following:

spaceship-bottom-right-corner

To move the spaceship, this game uses the iPhone’s built-in accelerometers. Unfortunately, the iOS Simulator cannot simulate the accelerometers. That means that from now on, you will need to run the app on your device to test it.

Note: If you are unsure how to put the app on your device, check out this extensive tutorial that explains how to obtain and install the certificates and provisioning profiles that allow Xcode to run apps on your device. It’s not as intimidating as it looks, but you do need to sign up for the paid Apple developer program.

Note: If you are unsure how to put the app on your device, check out this extensive tutorial that explains how to obtain and install the certificates and provisioning profiles that allow Xcode to run apps on your device. It’s not as intimidating as it looks, but you do need to sign up for the paid Apple developer program.

To move the spaceship with the accelerometers, you’ll obviously be rocking your device from side to side. During testing I found that this sometimes caused the screen to autorotate from landscape right to landscape left, which is really annoying when you’re in the middle of a heated battle.

This was the reason you used the Project Settings\General screen and in the Device Orientation, de-selected all options except for Landscape Right earlier.

Using the accelerometers from code is pretty straightforward through the new CoreMotion framework. There are two ways to get accelerometer data: pushed to your application at a specific frequency, and where you request the values when you need them. Apple recommends not having data pushed to your application unless timing is very critical (like a measurement or navigation service) since it can drain the batteries faster.

Your game has a natural place to read the accelerometer data, that’s in the update method that gets called by Sprite Kit for every loop. You will grab the these values to change the speed of the spaceship in this method.

You need to do some setup to use core motion but it is pretty easy.

First declare your intent to use the CoreMotion framework and bring it in through the new @import syntax. On the line before your #import "MyScene.h" add the following line:

@import CoreMotion;

This new syntax tells Xcode you wish to use the CoreMotion framework and also to expose the .h headers for you. Pretty neat, compared to the old way of accessing external frameworks.

Next you need some instance variables to keep track of the accelerometer values. You only store the values for two of the accelerometers; the “Z” one isn’t used by this game. Add the following lines to your implementation area:

@implementation MyScene
{
    . . .
    UIAccelerationValue _accelerometerX;
    UIAccelerationValue _accelerometerY;


    CMMotionManager *_motionManager;
}

Now create a couple of utility methods for using the accelerometers and to cleanup should we exit the game. Underneath the initWithSize method add the following methods:

- (void)dealloc
{
    [self stopMonitoringAcceleration];
    _motionManager = nil;
}

- (void)startMonitoringAcceleration
{
    if (_motionManager.accelerometerAvailable) {
        [_motionManager startAccelerometerUpdates];
        NSLog(@"accelerometer updates on...");
    }
}

- (void)stopMonitoringAcceleration
{
    if (_motionManager.accelerometerAvailable && _motionManager.accelerometerActive) {
        [_motionManager stopAccelerometerUpdates];
        NSLog(@"accelerometer updates off...");
    }
}

The start and stop methods check to make sure the capability is present on the device and if so tell it to start gathering data. The stop method will be called when you wish to turn off the data gathering.

A good place to activate the accelerometers is inside initWithSize. Add the following line to it underneath the [self addChild:_playerSprite]; line:

_motionManager = [[CMMotionManager alloc] init];
[self startMonitoringAcceleration];

Next, add the method that will be called to read the values and let your player change positions:

- (void)updatePlayerAccelerationFromMotionManager
{
    const double FilteringFactor = 0.75;
    
    CMAcceleration acceleration = _motionManager.accelerometerData.acceleration;
    _accelerometerX = acceleration.x * FilteringFactor + _accelerometerX * (1.0 - FilteringFactor);
    _accelerometerY = acceleration.y * FilteringFactor + _accelerometerY * (1.0 - FilteringFactor);

}

This bit of logic is necessary to filter – or “smooth” – the data that you get back from the accelerometers so that it appears less jittery.

Note: An accelerometer records how much gravity currently pulls on it. Because the user is holding the iPhone in her hands, and hands are never completely steady, there are a lot of tiny fluctuations in this gravity value. We are not so much interested in these unsteady motions as in the larger changes in orientation that the user makes to the device. By applying this simple low-pass filter, you retain this orientation information but filter out the less important fluctuations.

Note: An accelerometer records how much gravity currently pulls on it. Because the user is holding the iPhone in her hands, and hands are never completely steady, there are a lot of tiny fluctuations in this gravity value. We are not so much interested in these unsteady motions as in the larger changes in orientation that the user makes to the device. By applying this simple low-pass filter, you retain this orientation information but filter out the less important fluctuations.

Now that you have a stable measurement of the device’s orientation, how can you use this to make the player’s spaceship move?

Movement in games often works like this:

  1. Set the acceleration based on some form of user input, in this case from the accelerometer values.
  2. Add the new acceleration to the spaceship’s current speed. This makes the object speed up or slow down, depending on the direction of the acceleration.
  3. Add the new speed to the spaceship’s position to make it move.

Of course, you have a great mathematician to thank for these equations: Sir Isaac Newton!

You need some more instance variables to pull this off. There is no need to keep track of the player’s position because the SKSpriteNode already does that for you, but acceleration and speed are your responsibility.

Add these instance variables:

@implementation MyScene
{
    . . .
    float _playerAccelX;
    float _playerAccelY;
    float _playerSpeedX;
    float _playerSpeedY;

}

It’s good to set some bounds on how fast the spaceship can travel or it would be pretty hard to maneuver. Infinite acceleration sounds like a good idea in theory but in practice it doesn’t work out so well (besides, even Einstein thinks there are limits to how fast you can go).

Add the following lines directly below the #import statement:

const float MaxPlayerAccel = 400.0f;
const float MaxPlayerSpeed = 200.0f;

This defines two constants, the maximum acceleration (400 points per second squared) and the maximum speed (200 points per second).

Now add the following bit of logic to the bottom of updatePlayerAccelerationFromMotionManager:

if (_accelerometerY > 0.05)
{
    _playerAccelX = -MaxPlayerAccel;
}
else if (_accelerometerY < -0.05)
{
    _playerAccelX = MaxPlayerAccel;
}
if (_accelerometerX < -0.05)
{
    _playerAccelY = -MaxPlayerAccel;
}
else if (_accelerometerX > 0.05)
{
    _playerAccelY = MaxPlayerAccel;
}

This is a basic technique for controlling a sprite using the accelerometers. When the device is tilted to the left, you give the player maximum acceleration to the left. Conversely, when the device is tilted to the right, you give the player maximum acceleration to the right. Likewise for the up and down directions.

Note: You’re using the _accelerometerY value for the x-direction. That’s as it should be. Remember that this game is in landscape, so the Y-accelerometer runs from left to right in this orientation, and the X-accelerometer from top to bottom.

Note: You’re using the _accelerometerY value for the x-direction. That’s as it should be. Remember that this game is in landscape, so the Y-accelerometer runs from left to right in this orientation, and the X-accelerometer from top to bottom.

You’re almost there. The last step is applying the _playerAccelX and Y values to the speed and position of the spaceship. You will do this in the game’s update method. This method is called 60 times per second, so it’s the natural place to perform all of the game logic.

Add updatePlayer to the class:

- (void)updatePlayer:(NSTimeInterval)dt
{
    // 1
    _playerSpeedX += _playerAccelX * dt;
    _playerSpeedY += _playerAccelY * dt;
    
    // 2
    _playerSpeedX = fmaxf(fminf(_playerSpeedX, MaxPlayerSpeed), -MaxPlayerSpeed);
    _playerSpeedY = fmaxf(fminf(_playerSpeedY, MaxPlayerSpeed), -MaxPlayerSpeed);
    
    // 3
    float newX = _playerSprite.position.x + _playerSpeedX*dt;
    float newY = _playerSprite.position.y + _playerSpeedY*dt;
    
    // 4
    newX = MIN(_winSize.width, MAX(newX, 0));
    newY = MIN(_winSize.height, MAX(newY, 0));
    
    _playerSprite.position = CGPointMake(newX, newY);
}

If you’ve programmed games before (or studied physics), then this should look very familiar. Here’s how it works:

Add the current acceleration to the speed.

The acceleration is expressed in points per second (actually, per second squared, but don’t worry about that) but update: is performed a lot more often than once per second. To compensate for this difference, you multiply the acceleration by the elapsed or “delta” time, dt. Without this, the spaceship would move about sixty times faster than it should!

Clamp the speed so that it doesn’t go faster than MaxPlayerSpeed if it is positive or -MaxPlayerSpeed if it is negative. You could write this using an if statement instead:

However, I like the succinctness of the one-line version. fminf() makes sure the speed doesn’t become larger than MaxPlayerSpeed because it always picks the smallest of the two, while fmaxf() makes sure the speed doesn’t drop below -MaxPlayerSpeed because it always picks the largest value. It’s a neat little trick.

  1. Add the current acceleration to the speed.

    The acceleration is expressed in points per second (actually, per second squared, but don’t worry about that) but update: is performed a lot more often than once per second. To compensate for this difference, you multiply the acceleration by the elapsed or “delta” time, dt. Without this, the spaceship would move about sixty times faster than it should!

  2. Clamp the speed so that it doesn’t go faster than MaxPlayerSpeed if it is positive or -MaxPlayerSpeed if it is negative. You could write this using an if statement instead:

    if (_playerSpeedX < -MaxPlayerSpeed) 
    {
        _playerSpeedX = -MaxPlayerSpeed;
    }
    else if (_playerSpeedX > MaxPlayerSpeed) 
    {
        _playerSpeedX = MaxPlayerSpeed;
    }
    

    However, I like the succinctness of the one-line version. fminf() makes sure the speed doesn’t become larger than MaxPlayerSpeed because it always picks the smallest of the two, while fmaxf() makes sure the speed doesn’t drop below -MaxPlayerSpeed because it always picks the largest value. It’s a neat little trick.

  3. Add the current speed to the sprite’s position. Again, speed is measured in points per second, so you need to multiply it by the delta time to make it work correctly.
  4. Clamp the new position to the sides of the screen. You don’t want the player’s spaceship to go offscreen, never to be found again!
if (_playerSpeedX < -MaxPlayerSpeed) 
{
    _playerSpeedX = -MaxPlayerSpeed;
}
else if (_playerSpeedX > MaxPlayerSpeed) 
{
    _playerSpeedX = MaxPlayerSpeed;
}

One more thing, we need to measure time as differences (deltas) in time. The Sprite Kit update method gets called repeatedly with the current time. We will need to track the delta time between calls to the update method ourselves, so that your velocity calculations are smooth.

To track “delta” time add two more instance variables:

@implementation MyScene
{
    . . .
    NSTimeInterval _lastUpdateTime;
    NSTimeInterval _deltaTime;
}

Then replace the update stub with the actual implementation:

-(void)update:(NSTimeInterval)currentTime {
    /* Called before each frame is rendered */
    
    //To compute velocities we need delta time to multiply by points per second
    //SpriteKit returns the currentTime, delta is computed as last called time - currentTime
    if (_lastUpdateTime) {
        _deltaTime = currentTime - _lastUpdateTime;
    } else {
        _deltaTime = 0;
    }
    _lastUpdateTime = currentTime;

    [self updatePlayerAccelerationFromMotionManager];
    [self updatePlayer:_deltaTime];
}

That should do it.

The updatePlayerAccelerationFromMotionManager is called to calculate the players acceleration from the accelerometer values and save/clamp them.

Finally, the updatePlayer method is called to move the ship, making use of the delta time to compute the velocity.

Build and run the game on an actual device (not the simulator). You can now control the spaceship by tilting the device:

accelerometer

Tony Dahbura

Contributors

Tony Dahbura

Author

Over 300 content creators. Join our team.