How To Create A Breakout Game Using SpriteKit

Learn how to create a breakout game for iOS using SpriteKit! By Barbara Reichart.

Leave a rating/review
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Finishing Touches

As you play the game, you may have noticed that sometimes the ball can get super-fast or super-slow, depending on how you hit it with the paddle.

You can prevent these speed variations by overriding the default update: method for MyScene.m like so:

-(void)update:(CFTimeInterval)currentTime {
    /* Called before each frame is rendered */
    SKNode* ball = [self childNodeWithName: ballCategoryName];
    static int maxSpeed = 1000;
    float speed = sqrt(ball.physicsBody.velocity.dx*ball.physicsBody.velocity.dx + ball.physicsBody.velocity.dy * ball.physicsBody.velocity.dy);
    if (speed > maxSpeed) {
        ball.physicsBody.linearDamping = 0.4f;
    } else {
        ball.physicsBody.linearDamping = 0.0f;
    }
}

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!

Barbara Reichart

Contributors

Barbara Reichart

Author

Over 300 content creators. Join our team.