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
You are currently viewing page 5 of 5 of this article. Click here to view the first page.

Contents

Hide contents

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

40 mins

Adding Some Spin

For a nice effect, you can add some spin to the spaceship after a collision. This additional rotation doesn't influence the flight direction; it just makes the effect of the collision more profound (and the pilot more dizzy). Add a new constant to the top of GameScene.swift:

let playerCollisionSpin: CGFloat = 180

This sets the amount of spin to half a circle per second, which I think looks pretty good. Now add a new property to the GameScene class:

var playerSpin: CGFloat = 0

In checkShipCannonCollision(), add the following code just before the update the health bar methods:

playerSpin = playerCollisionSpin

Finally, add the following code to updatePlayer(_:) right before playerSprite.zRotation = playerAngle - 90 * degreesToRadians:

if playerSpin > 0 {
  playerAngle += playerSpin * degreesToRadians
  previousAngle = playerAngle
  playerSpin -= playerCollisionSpin * CGFloat(dt)
  if playerSpin < 0 {
    playerSpin = 0
  }
}

The playerSpin has effectively override the ship's display angle for the spin duration without affecting the velocity. The amount of spin quickly decreases over time, so that the ship comes out of the spin after one second. While spinning, you update previousAngle to match the spin angle so that the ship doesn't suddenly snap to a new angle after coming out of the spin.

Build and run and set that ship spinning!

Where to Go from Here?

You can download the completed version of the project so far using the Download Materials button at the top or bottom of this tutorial.

You've seen how you can use triangles to breathe life into your sprites with the various trigonometric functions to handle movement, rotation and even collision detection.

But there's more to come in Part 2 of the 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.

If you want to learn more about SpriteKit and games programming, read 2D Apple 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.