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 7 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

Adding Some Spin

For an additional effect, you can add spin to the spaceship after a collision. This is additional rotation that doesn't influence the flight direction. It just makes the effect of the collision more profound (and the pilot dizzy). Add a new instance variable in the implementation block:

@implementation MyScene
{
    ...
    float _playerSpin;
}

In checkCollisionOfPlayerWithCannon, add the following line inside the collision detection block:

if (distance <= CannonCollisionRadius + PlayerCollisionRadius)
{
    ...
    _playerSpin = 180.0f * 3.0f;
}

This sets the amount of spin to a circle and a half, which I think looks pretty good. Now at the bottom of updatePlayer, add the following code to add spin to the rotation:

_playerSprite.zRotation += -SK_DEGREES_TO_RADIANS(_playerSpin);

if (_playerSpin > 0.0f)
{
    _playerSpin -= 2.0f * 360.0f * dt;
    if (_playerSpin < 0.0f)
    {
        _playerSpin = 0.0f;
    }
}

The amount of spin quickly decreases over time – I chose a speed of 720 degrees per second. Once the spin has reached 0, it stops.

Build and run and set that ship spinning!

Where to Go from Here?

Here is the full example project from the tutorial up to this point.

Triangles are everywhere! You've seen how you can use this fact to breathe life into your sprites with the various trigonometric functions.

You have to admit, it wasn’t that hard to follow along, was it? Math doesn’t have to be boring if you can apply it to fun projects, such as making games.

But there's more to come: in Part 2 of this Trigonometry for Game Programming series, you'll add missiles to the game, learn more about sine and cosine, and see some other useful ways to put the power of trig to work in your games.

In the meantime, drop by the forums to share how it's going for you so far! Or if you really can't wait until part 2, why not brush up on some more Sprite Kit with some of our other tutorials. Alternatively, if you want to start diving into more game development why not take a look at our book, iOS Games by Tutorials.

Credits: The graphics for this game are based on a free sprite set by Kenney Vleugels. The sound effects are based on samples from freesound.org.

Tony Dahbura

Contributors

Tony Dahbura

Author

Over 300 content creators. Join our team.