How To Create A Breakout Game Using SpriteKit

Learn how to create a breakout game for iOS using SpriteKit!

Barbara Reichart
Dec 4 2013 · Beginner · Article · 40 mins

Version

Other, Other, Other

SpriteKit is Apple’s new game development framework for iOS and Mac OS. Not only does it come with some great graphics capabilities, but it also includes a physics engine which looks a lot like Box2D. Best of all, you do all the work using straight Objective-C!

There’s a lot you can do with SpriteKit, and a great way to start learning about how it works is to create a simple game.

In this tutorial, you are going to learn how to create a Breakout game using SpriteKit step-by-step, complete with collision detection, ball bouncing using physics effects, dragging the paddle via touches, and win/lose screens.

The SpriteKit World in Theory

Before you go any further, do you have a moment to talk… about physics?

In SpriteKit you work in two environments. The graphical world that you see on the screen and the physics world, which determines how objects move and interact.

The first thing you need to do when using SpriteKit physics is to change the world according to the needs of your game. The world object is the main object in SpriteKit that manages all of the objects and the physics simulation. It also sets up the gravity that works on physics bodies added to it. The default gravity is -9.81 thus similar to that of the earth. So, as soon as you add a body it would “fall down”.

Once you have created the world object, you can add things to it that interact according to the principles of physics. For this the most usual way is to create a sprite (graphics) and set its physics body. The properties of the body and the world determine how it moves.

Bodies can be dynamic objects (balls, ninja stars, birds, …) that move and are influenced by physical forces, or they can be static objects (platforms, walls, …) that are not influenced by those forces. When creating a body you can set a ton of different properties like shape, density, friction and many more. Those properties heavily influence how the body behaves within the world.

When defining a body, you might wonder about the units of their size and density. Internally SpriteKit uses the metric system (SI units). However within your game you usually do not need to worry about actual forces and mass, as long as you use consistent values.

Once you’ve added all of the bodies you like to your world, SpriteKit can take over and do the simulation. Now that you have a basic understanding of how things should work, let’s see it in code! Time for some Breakout!

Getting Started

Start by creating a new project. For this start up XCode, go to File\New\Project and choose the iOS\Application\SpriteKit Game template. Set the product name to BreakoutSpriteKitTutorial, select Devices>iPhone and then click Next. Select the location on your hard drive to save your project and then click Create.

Your game will need some graphics. You probably want to have at least a graphic for the ball, the paddle, the bricks, and a background image. You can download them from here. Drag and drop the files from Finder on to your XCode project. Make sure that the checkmark for Copy items into destination group’s folder (if needed) is ticked and press the Finish button.

Open MyScene.m. This class creates your game scene. The template includes some extra code that you will not need. So, replace the contents of the file with the following:

The code here is very basic. First, you define a few constants that will help you to identify the game objects. Then, initWithSize: initializes an empty scene with a specified size, creates a sprite using an image, positions it in the middle of the screen, and adds it to the scene.

Now you have an barebones project which displays a background image. However, the screen is still in portrait mode and you want Breakout to work in landscape mode instead. For this you need to do two things:

Select the project root in Xcode, then select the BreakoutSpriteKitTutorial target, make sure that the General tab is selected, and set the orientation to just landscape by ensuring that only the two landscape checkboxes are checked as shown below:

If you’ve done the first step and load the app, you will realize that it still looks weird. Parts of the background are not displayed on screen. To fix this, you need to switch to ViewController.m.

Remove the implementation for viewDidLoad and instead, add the following code:

Setting up your scene in viewWillLayoutSubviews ensures that the view is in the view hierarchy and hence laid out properly. In contrast, this does not work correctly in viewDidLayout because the size of the scene is not known at that time. You can find a much more detailed explanation for this in the Switching to Landscape Orientation section of the SpriteKit Tutorial for Beginners.

An-Ever-Bouncing Ball

Once you have a nice clean scene in landscape mode, it is time to play around with the physics of SpriteKit. Open MyScene.m and add the following line of code to the end of initWithSize: (right after the line adding the background to the scene):

self.physicsWorld.gravity = CGVectorMake(0.0f, 0.0f);

The above changes the gravity of the game world, with one line of code. Don’t let this kind of power go to your head ;). The default gravity in SpriteKit is 0 along the x-Axis and -9.8 along the y-Axis simulating that of the earth. However, for your Breakout game you do not want any gravity. So, you just set the gravity to zero along both axes.

Next you should create an invisible barrier around the screen. This will effectively cage the ball on screen, ensuring that it cannot escape.

No escape for the ball.

To do this, add the following code to the end of initWithSize: (right after the last line you added) in MyScene.m:

You create an SKPhysicsBody. SKPhysicsBodies are used to add physics simulation to a node. In this case, you create an edge-based body which does not have mass or volume, and is unaffected by forces or impulses.

You can set a physics body for every node. Here, you attach it to the scene. Note: The coordinates of the SKPhysicsBody are relative to the position of the node.

Set the friction to 0.0f so that the ball will not be slowed down when colliding with the border barrier. Instead, you want to have a perfect reflection, where the ball leaves along the same angle that it hit the barrier.

Perfect reflection

At this point you have this amazing cage, but you cannot see its effects. To actually see how the cage works, you need to add the ball. Go ahead and add the following lines of code to the end of initWithSize: (right after the previous code):

No surprises here. You simply create a sprite, name it for later reference, set its position relative to the scene, and add it to the scene.

You create a volume-based body for the ball. In contrast to the edge-based body you created to form the barrier around the screen, this physics body is affected by forces or impulses, and collisions with other bodies. Here you create a physics body with the form of a circle that has exactly the same size as the ball sprite.

Next, you set up a few properties for the physics body. You’ve already worked with friction, and it should be quite clear what this line does – it simply removes all friction.

Restitution refers to the bounciness of an object. You set the restitution to 1.0f, meaning that when the ball collides with an object the collision will be perfectly elastic. In plain English, this means that the ball will bounce back with equal force to the impact.

LinearDamping simulates fluid or air friction by reducing the body’s linear velocity. In the Breakout game the ball should not be slowed down when moving. So, you set the restitution to 0.0f.

AllowsRotation does exactly what the name implies. It either allows rotation of the body or not. Here you do not want the ball to rotate.

Note: Usually, it’s best to have the physics body be fairly similar to what the player sees. For the ball it’s very easy to have a perfect match. However, with more complex shapes you’ll have to get a bit more creative. This is where you’ll need to be careful since very complex bodies can exact a high toll on performance.

It’s time to get the ball rolling (bouncing, actually). Add the following code right after the previous lines:

[ball.physicsBody applyImpulse:CGVectorMake(10.0f, -10.0f)];

This new code applies an impulse (think of it like the propulsion from a jet pack thruster) to the ball to get it moving in a particular direction (in this case, diagonally down to the right). Once the ball is set in motion, it will simply bounce around the screen because of the barrier around the screen!

Now it’s time to try it out! When you compile and run the project, you should see a ball continuously bouncing around the screen – cool!

They see me bouncin’, they hatin’ :D

Adding the Paddle

It wouldn’t be a Breakout game without a paddle, now would it?

Construct the paddle (and its companion physics body) in initWithSize: in MyScene.m by adding this code just after you create and configure the ball:

The above code gets the touch and uses it to find the location on the scene where the touch occurred. Next, it uses bodyAtPoint: from physicsWorld to find the body (if any) at that location.

Next, it checks whether there was a body at the tap location and if yes, whether that body is the paddle. This is where the object names you set up earlier come in to play – you can check for a specific object by checking its name. If the object at the tap location is a paddle, then a log message is sent to the console and isFingerOnPaddle is set to YES.

Now you can build and run the project again. When you tap the paddle, you should see a log message in the console.

If yes, then you need to update the position of the paddle depending on how the player moves their finger. To do this, you get the touch location and previous touch location.

Get the SKSpriteNode for the paddle.

Take the current position and add the difference between the new and the previous touch locations.

Before repositioning the paddle, limit the position so that the paddle will not go off the screen to the left or right.

Set the position of the paddle to the position you just calculated.

Note: You might have noticed that the code directly manipulates the position of the paddle. You can do this because you made the paddle static. You should never change the position of a dynamic body directly, as it can break the physics simulation and lead to really weird behavior.

Don’t believe me? Make the paddle dynamic and set a low gravity, e.g. this

self.physicsWorld.gravity = CGPointMake(-0.1, -0.1);

Looks quite messed up, doesn’t it?

The only thing left in touch handling is to do some cleanup in touchesEnded:withEvent: as follows:

Here, you set the isFingerOnPaddle property to NO. This ensures that when the player takes their finger off the screen and then taps it again, the paddle does not jump around to the previous touch location.

Perfect! When you build and run the project now, the ball will bounce around the screen and you can influence its movement using the paddle.

SpriteKit Makes First Contact!

No! Not that type of first contact. (image by DeviantArt user hugoo13, Creative Commons Licensed)

So far, you have a ball that bounces around the screen and a paddle you can move around via touch. While this is really fun to toy around with, to make it a game you need a way for your player to win and lose the game. Losing should happen when the ball touches the bottom of the screen instead of hitting the paddle. But how do you detect this scenario using SpriteKit?

SpriteKit can detect the contact between two physics bodies. However, for this to work properly, you need to follow a few steps to set things up a certain way. I’ll give you a short overview here and explain each of the steps in more detail later. So, here you go:

Set up physics body bit masks: In your game you might have several different types of physics bodies – for example, you can have the player, enemies, bullets, bonus items etc. To uniquely identify these different types of physics bodies, each physics body can be configured using several bit masks. These include:

categoryBitMask: This bit mask identifies the category a body belongs to. You use categories to to define a body’s interaction with other bodies. The categoryBitMask is a 32-bit integer, where each bit represents one category. So you can have up to 32 custom categories in your game. This should be enough for most games to set up a separate category for each object type. For more complex games it can be useful to remember that each body can be in several categories. So through smart design of the categories you could even overcome the limitation of 32 categories.

contactTestBitMask: Setting a bit in this bitmask causes SpriteKit to notify the contact delegate when the body touches another body assigned to that particular category. By default, all bits are cleared – you are not notified about any contacts between objects. For best performance you should only set bits in the contacts mask for interactions you are really interested in.

collisionBitMask: Here, you can define which bodies can collide with this physics body. You can use this, for example, to avoid collision calculations for a very heavy body when it collides with a much lighter body as this would only make negligible changes to the heavy body’s velocity. But you can also use it to allow two bodies to pass right through each other.

Set and implement the contact delegate: The contact delegate is a property of SKPhysicsWorld. It will be notified when two bodies with the proper contactTestBitMasks begin and end colliding.

Note: Bit masks?!? In case you’ve never worked with bit masks, don’t panic! At first glance they might look complicated, but they are really useful.

So what is a bitmask? A bitmask is a multi-digit binary number. Something like this: 1011 1000. Not so complicated at all.

But why are they useful? Well, they allow you to get state information out of a binary number and give you the ability to change a specific bit in a binary number to set a specific state. You can do this with the binary operators AND and OR, like so:

Bitmask power :)

This allows you to store a lot of information in a really compact way using just one variable and still be able to access and manipulate the stored information.

So how do you do all this in code?

First, create constants for the different categories. Do this by adding the following lines below the other constants for the category names in MyScene.m:

The above defines four categories. You do this by setting the last bit to 1 and all other bits to zero. Then using the << operator you shift this bit to the left. As a result, each of the category constants has only one bit set to 1 and the position of the 1 in the binary number is unique across the four categories.

For now you only need the category for the bottom of the screen and the ball, but you should set up the others anyway as you will probably need them later on as you expand the gameplay.

Once you have the constants in place, create a physics body that stretches across the bottom of the screen. Try to do this by yourself since this uses principles you've already learnt when creating the barriers around the screen edges. (Name the node containing the physics body bottom since you’ll be configuring that node in later steps.)

[spoiler title=”Create an edge-based body that covers the bottom of the screen”]
Add the following to initWithSize: in MyScene.m:

This code might appear a little weird to you, so let me walk you through.

Create two local variables to hold the two physics bodies involved in the collision.

Check the two bodies that collided to see which has the lower categoryBitmask. You then store them into the local variables, so that the body with the lower category is always stored in firstBody. This will save you quite some effort when reacting to contacts between specific categories.

Profit from the sorting that you did just before. You only need to check whether firstBody is in the ballCategory and whether secondBody is in the bottomCategory to figure out that the ball has touched the bottom of the screen, as you already know that secondBody could not possibly be in the ballCategory if firstBody is in the bottomCategory (because bottomCategory has a higher bit mask than ballCategory). For now react with a simple log message.

It’s time to try out your code again. Build and run your game again and if you’ve done everything correctly, you should see the log message in the console every time the ball misses the paddle and hits the bottom of the screen. Like this:

First contact has been made :)

Adding a Game Over Scene

Unfortunately, your player cannot see log messages when they lose the game. Instead, when they lose, you want to show him/her some sort of visual indication on screen. You must create a little game over scene for that purpose.

Go to File\New\File…, choose the iOS\Cocoa Touch\Objective-C class template, and click Next. Name the class GameOverScene, make it a subclass of SKScene, click Next, and then Create.

Switch to GameOverScene.h and add the following method prototype before the @end line:

-(id)initWithSize:(CGSize)size playerWon:(BOOL)isWon;

This new initializer adds a parameter indicating whether the player has won or lost. This allows you to implement only one scene for both victory and defeat. Very convenient :)

This code creates three blocks with some padding so that they are centered on the screen.

Some useful variables like the number of blocks you want and their width.

Here you calculate the x offset. This is the distance between the left border of the screen and the first block. You calculate it by subtracting the width of all three blocks and their padding from the screen width and then dividing it by two.

Create three blocks, configure each with the proper physics properties, and position each one using blockWidth, padding, and xOffset.

The blocks are now in place. Build and run your game and check it out!

Breakout blocks at the beginning of the game. Nice and orderly.

Not quite as expected…

Hmm … not quite what you wanted, right? The blocks move around instead of being destroyed when touched by the ball.

In order to listen to collisions between the ball and blocks, you must update the contactTestBitMask of the ball like this (note that this is an existing line of code in initWithSize: – you simply need to add an extra category to it.):

ball.physicsBody.contactTestBitMask = bottomCategory | blockCategory;

The above executes a bitwise OR operation on bottomCategory and blockCategory. The result is that the bits for those two particular categories are set to one while all other bits are still zero. Now, collisions between ball and floor as well as ball and blocks will be sent to to the delegate.

The only thing left to do is to handle the delegate notifications accordingly. Add the following to the end of didBeginContact::

if (firstBody.categoryBitMask == ballCategory && secondBody.categoryBitMask == blockCategory) {
[secondBody.node removeFromParent];
//TODO: check if the game has been won
}

The above lines check whether the collision is between the ball and a block. If this is the case, you remove the block involved in the collision.

Hopefully, you have a good understanding of bit masks in general and the contactTestBitMask in particular. As you read earlier, bodies also have a second bit mask – the collisionBitMask. It determines whether two bodies interact with each other. This allows you to control whether the ball bounces off the bricks or flies right through them, for instance.

If you want to practice working with bit masks, set the collisionBitMask of the ball so that it goes straight through blocks while destroying them.

[spoiler title=”Using collisionBitMask”]

ball.physicsBody.collisionBitMask = paddleCategory;

Setting the collisionBitMask to paddleCategory means that the ball now only physically interacts with the paddle and not the blocks. For the barriers around the screen everything stays the same as they do not have any category assigned.

block.physicsBody.collisionBitMask = 0;

The above line sets the collisionBitMask for the block to zero. This sets the block to not react to other bodies hitting it.
[/spoiler]

Have you overcome the challenge and tasted the thrill of victory? Time to give your player the same satisfaction of tasting victory :]

Winning the Game

To let the player actually win the game, add this method to MyScene.m.

The new method checks to see how many bricks are left in the scene by going through all the scene’s children. For each child, it checks whether the child name is equal to blockCategoryName. If there are no bricks left, the player has won the game and the method returns YES.

Now, go back to didBeginContact: and replace the TODO line in the final if condition with the following:

update: is called before each frame is rendered. In the case of MyScene.m, there is no update: method since the default implementation has been used till now. Here, you override it with your own implementation.

You get the ball and check its velocity, essentially the movement speed. If it’s too high, you increase the linear damping so that the ball will eventually slow down.

If you compile, run, and play the game, you should see the ball go back to a normal speed level when the speed increases too much.

Note: You might be tempted to prevent the ball from becoming too fast by influencing its velocity directly since that might give you a little more control over its movement. This was not allowed in Box2D, and is probably not a good idea in SpriteKit either.

Gimme the Code!

Here’s the full code for the SpriteKit Breakout Game that you’ve made in this tutorial.

Where To Go From Here?

Obviously, this is a quite simple implementation of Breakout. But now that you have this working, there’s a lot more you can do. You could extend this code to give the blocks hit points, have different types of blocks, and make the ball have to hit some of them (or all of them) a number of times before they are destroyed. You could add blocks which drop bonuses or power-ups, let the paddle shoot lasers toward the blocks, whatever you dream up!

Let me know if you have any tips or suggestions for better ways to do things, and hope this comes in handy!