Trigonometry for Game Programming: Part 1/2

Learn Trigonometry for Game Programming in this 2-part tutorial series, where you’ll learn the theory and then practice by making a space shooter game! By Matthijs Hollemans.

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: Part 1/2

65 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 HelloWorldLayer
{
    ...
    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.rotation += _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 Cocos2D with some of our other tutorials. Alternatively, if you want to start diving into more game development why not take a look at the games starter kits available on this site.

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.

Matthijs Hollemans

This is a post by iOS Tutorial Team member Matthijs Hollemans, an experienced iOS developer and designer. You can find him on and Twitter.