SpriteKit Game From Scratch, Swift 2.0, part 4

Swift 2.0, Xcode 7.2
Part 4 of the SpriteKit Game tutorial

 

 

Introduction

Hi and thanks for following this tutorials so far! This would be the fourth and final part.
So far, if you have followed the previous 3 parts you should have a working simple game.
The current project files are located here: SpriteKit tutorial part 3 files
In this part we’ll look into adding some extra features to our game, to make it a little bit more fancy looking and more fun to play.

The Plan

We’ll be looking into:

  • adding visual effects
  • adding audio effects
  • background music
  • simulating motion

I might add more later on.
Let’s get to it.

Visual Effects

A game is not fun without visual effects. For our little game it would be nice if the bullets create a little explosion when they hit. For this purpose we’ll use the SKEmitterNode. Usually you’ll end up having more than one, so I would suggest creating a new group, call it Emitters and then right click, create new file and select iOS->Resources->SpriteKit Particle File:

We’ll select the type ‘Fire‘ and call it ‘Explosion1
This will create 2 files: explosion1.sks and the spark.png
The png file is the texture that the emitter uses, you could use a custom texture if you want, but in our case we’ll just stick with the spark.
Open the .sks file ( sometimes you won’t see anything – try closing Xcode and re-opening it, if that happens ), feel free to play around with it, however here are the settings I made for our explosion:

We’ll create a new function to generate an explosion, so we can just call it whenever we need it. The function will take on parameter – the point where we are going to need it – in our case the point of contact:

We are passing a CGPoint, creating the SKEmitterNode at that point, then in 0.2 seconds removing it, adding it to the objectsToRemove array.
Then we’ll call it at the top of the didBeginContact like this:

This is enough to add the effect for the enemy bullets.

To add the explosion to the Hero’s bullets, just modify the custom contact method checkIfHit like this:

We now have explosion effects to our bullets – great !
Let’s go back and change our contact method for the Enemy to be using the gameOver, rather than our Hero’s HP.
Please change the bottom of the didBeginContact like this:

Run your project and you should now have explosions on both type of bullets.

Audio FX and Playing Music

First we need to import a new framework to our game scene. All the way at the top, right below import SpriteKit, add this line:

Then right before didMoveToView, below the ‘var shootingAllowed: Bool = true‘ add this:

We are adding 2 separate players – one for FXs and one for the music.
Feel free to use your own audio files, but I created a simple loop in Garage band and an explosion effect, feel free to download and use them:
Music Loop
Explosion FX
Download the 2 files and drag them into your project.
Now we’ll create our method for playing the music at the bottom of our scene:

We could’ve created a simpler method, but this will allow you to use it for other things as well. We need to call it at the start of our game in didMoveToView like this:

Loops: -1 means that it will loop forever.
We also need to stop it and restart it whenever we restart the game, so add this to the end of
your restartGame() method:

To play our explosion audio we’ll make a much more simpler method, add this to the bottom of the scene:

Now, where to play it ? Well, the easiest way is in our explosion method, since they should happen at the same time. Add it to the top of the explosion1 method and you should have it looking like this:

Play your game and you should now have both the music and the Audio FX on hit!

Simulating motion

Let’s first see about creating a new emitter. This can be used to simulate rain, snow or stars in order to simulate motion in space, just as before create a new emitter, but this time choose type: rain and name it ‘stars’ . Play around with it however these are the settings I got:

We’ll create a new function to add the stars:

As you can see I am choosing zPosition to be 1 – above the background image, but underneath everything else ( feel free to just add a new layer to the struct and do it this way… )
Now we only need to call our new function in the didMoveToView, right after the setupBg():

Ok, we got our stars, you could even comment the setupBg() and you’ll see that the stars do create a feeling of motion. If you haven’t changed the default background for your project it’s probably gray, you can change it to black really easily – just select your GameScene.sks and then change it in the Attribute Inspector:

Another great way of simulating motion in a game is to add custom moving objects – like spaceships, planets, buildings, mountains ..etc. So let’s try and do that.
Let’s add some flying asteroids in the background – add these 3 to your project ( curtesy of OpenGameArt.org ) :

I’ll rename my pngs to red.png , grey1.png and grey2.png
Then I am just going to create 3 textures in our global.swift file like this:

Then we’ll create our method for calling the Red Asteroid at the bottom of the scene:

Call the method in the didMoveToView() and in the restartGame()
Run your game and you should now see your asteroid flying down through the screen.
But what if you wanted to spawn multiple asteroids ? And for them to be with a random texture and size ?
Now that’s a bit more work, but it’s quite achievable 🙂
First we’ll add our own method for a random Int( I’ll also add the one for a random Float ) to the bottom of our scene:

Now we’ll create our Asteroid spawning action:

I know it might look a bit confusing at first, but everything in this method should already be familiar to you, maybe besides cases , but that’s pretty obvious. You can also read up on ‘flow control’
Basically we are creating one big SKAction that creates a random Asteroid SKSpriteNode and then running a sequence of the Creation Action and a WaitAction. Pretty simple ! 🙂
It you want to use Physics you will need to add a physics body to each Asteroid as well.
Then you can just use the gravity or apply velocity to them instead.
You should be able to figure that on your own by now, but here is how it would look.
Now we’ll also prep some more things to make the Asteroid sizes random as well.
Add this in your global.swift file, below the Asteroid textures:

Don’t forget to change the gravity ( we set it at the top of the scene ):

Here is the refined method, in order to use PhysicsBody and Gravity and random sizes:

Please look at all the notes in the code, at the end I also added a bit of code to add a random rotation to each asteroid. In order to make the rotation work we need to add the rotation actions, I added them to the global.swift :

Please note that I add a lot of things to the global.swift, which is fine for a small project like this, but it’s not a best practice. For bigger projects, where you would want to fine tune and improve performance you’ll need to add methods and variables in a way that they are only accessible to the classes they are need  by.

Don’t forget to enumerate for the asteroids and remove any of them that go out of the screen. If you don’t you’ll end up with a ton of nodes and your performance will drop. Just look up the method we used for removing of the bullets 😉

Run your game and you should have this:

finalScene

Bonus – moving hero !

Let’s see how to add user interaction to the Hero.
We’ll add two methods – one for moving the hero to wherever we tap on the screen and another to follow your finger if you just like to drag it across. Please test this on a real device.

First method will go in touchesBegan:

Second method for the dragging needs to go into a method we haven’t used yet – touchesMoved, so you can just add that to the game scene:

Run your game and you should now be able to move your Hero using your finger! Congratz ! 🙂
You can find the full project here in my repo:
SpriteKit tutorial part 4 files
You can find the previous parts here:
Part 1
Part 2
Part 3

What next ?

You could replace the Asteroid textures with textures of buildings or mountains and have them scroll from right to the left in order to create a typical scrolling game.
What if you wanted to add effects to the bullets ? How about adding a SKParticleEmitter to each bullet ?
Do you think you can make a particle emitter look like a jet engine ? How about a torch ? Play around with the variables to see the results – speeds, gravity, sizes. See what you can do if you se a custom mass to an asteroid with .physicalBody.mass . Mass is a CGFloat.

Let me know if you have questions or comments below! Cheers !