Sprite Kit Tutorial: Space Shooter

A Sprite Kit tutorial that teaches you how to make a space shooter game. In the process, you’ll learn about accelerometers, textures, and scrolling too! By Tony Dahbura.

Leave a rating/review
Save for later
Share

This is a post by Tutorial Team Member Tony Dahbura, an independent iOS developer with FullMoon Manor LLC. You can also find him on .

Make a Space Shooter iPhone game!

Make a Space Shooter iPhone game!

Note from Ray: Tony has ported this popular tutorial from Cocos2D to Sprite Kit. We hope you enjoy!

In this Sprite Kit tutorial, you’ll learn how to make a space shooter game for the iPhone.

You’ll pilot a space ship with the accelerometer, and blast your way through a field of dangerous asteroids with your trusty laser gun!

If you’re a complete beginner to making iPhone games using Sprite Kit, this tutorial is for you. You’ll learn how to make a complete game from scratch, with no prior experience necessary.

If you’re completely new to programming in general you might want to check out this slightly easier introduction first.

This Sprite Kit tutorial is also good for intermediate developers, because it covers some neat effects such as parallax scrolling, using texture atlas’, accelerometer movement, particle emitters and physics engines.

Without further ado, let’s get blasting!

Create the Project

Let’s start by creating a Xcode skeleton for your project – start up Xcode, select File\New\Project…, choose iOS\Application\SpriteKit Game template, and click Next:

Select SpriteKit Template

Enter SpaceShooter for the Product Name, iPhone for Devices, and click Next:

spaceshooterwindow

Choose somewhere on your drive to save the project, and click Create. Then click the play button in the upper left to run the project as-is. You should see the following after clicking on the Hello, World! screen:

First Run with Template Code

In this tutorial, you’ll mainly be working with the MyScene.m file. Before you start coding, let’s get some space game stuff added to your project.

Adding Resources

To make this iPhone game, you are going to need some art and sound effects with a space theme.

But don’t whip out a paint program quite yet – luckily Vicki Wenderlich has made some cool space game art, and we have pulled some cool sounds and other things together as resources you can use in this project!

So go ahead and download the space game resources and unzip them to your system.

Once you’ve unzipped the resources drag the whole folder to the SpaceShooter folder in your Xcode project. Make sure that Copy items into destination group’s folder (if needed) is checked, and click Finish. When you’re done your Groups and Files tree should look something like this:

Project After Adding Resources

If you’re curious, feel free to take a peek through the contents of the folders you just added to your project.

Here’s what’s inside:

  • Icons: Some images that you’ll use to create the icons for the game when it is on your phone. Little details, but important for that professional look and feel.
  • Backgrounds: Some images that you’ll use to create a side-scrolling background for the game. Includes an image of some space dust (that will go in front and move a little bit faster). There are some other images you can use to spruce up your game if you want to.
  • Classes: Some additional classes for you to use to implement parallax scrolling (will discuss in a bit). Sprite Kit, unlike Cocos 2D does not contain built-in parallax scrolling, and what would a space shooter game be without a cool background rolling by?
  • Particles: Some special effects we’ll be using to create the effect of some stars flying by, created with Xcode’s built in particle emitter tool.
  • Sounds: Some space-themed background music and sound effects, created with Garage Band and cxfr.
  • SpaceShooter.atlas: Contains a Xcode generated Texture Atlas we’ll be using in the game, including the asteroid, space ship, etc. Texture Atlas’ offer the advantage of fast rendering and conserve memory usage for games.

In case you’re wondering why we’re combining all those images into a large image like this, it’s because it helps conserve memory and improve performance while making the game run faster. There is a full tutorial on Texture Atlas’ available here.

It’s a good practice to get into, so we’re starting you out with it early! :]

Setting up your Project

Let’s begin by getting the icons in place so the app stands out on your iPhone.

Start by expanding the Icons folder under Resources. Select the Images.xcassets in the Groups and Files tree. Click AppIcon and then drag each png file from the Icons folder into the AppIcon window. They will be auto-placed for you in the proper slots. When done your window should look like this:

Project-After-Icons-Added

Before you begin writing the game, you’ll need to make a few changes to support the game in landscape mode versus portrait.

Switching to Landscape Orientation

First, open your target setting by clicking your SpaceShooter project in the Project Navigator, selecting the SpaceShooter target. Then, in the Deployment Info section make sure General is checked at the top, uncheck Portrait so only Landscape Left and Landscape Right are checked in the Device Orientation area, as shown below:

Landscape Settings

Build and run your project, and all seems to work:

LandscapeApp-700x394

Or does it? More on this later.

Adding a Space Ship

Open MyScene.m and replace all the contents below the #import "MyScene.h" line with the following:

@implementation MyScene
{
    SKSpriteNode *_ship;    //1
}

-(id)initWithSize:(CGSize)size {    
    if (self = [super initWithSize:size]) {
        /* Setup your scene here */
        //2
        NSLog(@"SKScene:initWithSize %f x %f",size.width,size.height);

        //3
        self.backgroundColor = [SKColor blackColor];

#pragma mark - TBD - Game Backgrounds

#pragma mark - Setup Sprite for the ship
        //Create space sprite, setup position on left edge centered on the screen, and add to Scene
        //4
        _ship = [SKSpriteNode spriteNodeWithImageNamed:@"SpaceFlier_sm_1.png"];
        _ship.position = CGPointMake(self.frame.size.width * 0.1, CGRectGetMidY(self.frame));
        [self addChild:_ship];

#pragma mark - TBD - Setup the asteroids

#pragma mark - TBD - Setup the lasers

#pragma mark - TBD - Setup the Accelerometer to move the ship 

#pragma mark - TBD - Setup the stars to appear as particles

#pragma mark - TBD - Start the actual game

    }
    return self;
}


-(void)update:(NSTimeInterval)currentTime {
    /* Called before each frame is rendered */
}

@end

Let’s go over this step-by-step.

  1. At the top you define a variable to keep track of your trusty ship which you are about to add to the scene.
  2. You log out the size of the scene, which will yield interesting results shortly.
  3. Here you make the background color of the scene to black by setting the backgroundColor property.
  4. Adding a sprite to a Sprite Kit scene is really easy, you just use the spriteNodeWithImageNamed method, and pass in the name of the image. You then set the position of the sprite, and call addChild to add it to the scene. Here you set the space ship to be at the left edge of the screen and centered on the Y axis.
  5. The pragma marks will be used throughout, to guide you in building out the rest of the game. They are a glimpse into the future… Pragma marks also allow you to quickly jump to those locations in your source file by selecting the menu drop down on the far right over your edit window.

Build and run (use iPhone Retina (4 inch)), and… wait a minute, the ship looks a bit too large! Also, if you look at the console output you’ll see the following:

SpaceShooter[22664:a0b] SKScene:initWithSize 320.000000 x 568.000000

Your scene thinks its width is 320 and its height is 568 – which it is not! To see what’s happening, take a look at the ViewController.m's viewDidLoad method:

- (void)viewDidLoad
{
    [super viewDidLoad];
 
    // Configure the view.
    SKView * skView = (SKView *)self.view;
    skView.showsFPS = YES;
    skView.showsNodeCount = YES;
 
    // Create and configure the scene.
    SKScene * scene = [MyScene sceneWithSize:skView.bounds.size];
    scene.scaleMode = SKSceneScaleModeAspectFill;
 
    // Present the scene.
    [skView presentScene:scene];
}

This creates the scene with a size as the bounds of the view. However, when viewDidLoad is called, the view has not yet been added to the view hierarchy and hence it hasn’t responded to layout changes yet. So, the view bounds might not be correct yet, and this probably isn’t the best time to start up the scene.

The solution is to move the start up code to a later point in the process. In the ViewController.m file, replace the viewDidLoad method with the following:

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    // Configure the view.
    // Configure the view after it has been sized for the correct orientation.
    SKView *skView = (SKView *)self.view;
    if (!skView.scene) {
        skView.showsFPS = YES;
        skView.showsNodeCount = YES;

        // Create and configure the scene.
        MyScene *theScene = [MyScene sceneWithSize:skView.bounds.size];
        theScene.scaleMode = SKSceneScaleModeAspectFill;
        
        // Present the scene.
        [skView presentScene:theScene];
    }
}

Build and run, voila, the coordinates output to the screen are correct and your ship is sized a bit better! The viewWillLayoutSubviews has already gone through proper orientation, which is why you use the size from here instead.

Landscape Run

Console output confirms your success:

SpaceShooter[22768:a0b] SKScene:initWithSize 568.000000 x 320.000000

At this point you have a project setup to launch correctly in landscape mode and all the coordinates are working as they should.

Tony Dahbura

Contributors

Tony Dahbura

Author

Over 300 content creators. Join our team.