Simple Sprite Kit game tutorial- Part2

In the first part of the series, we created the basics scrolling background and a flying spaceship.

iOS Simulator Screen shot Oct 28, 2013 10.51.25 PM

In this part we are going to:

  1. Adding Missile with which spaceship can collide with
  2. Show end of game screen when spaceship collides with missile and give replay option
We are gonna add method to display missile on the screen, add this method at the end on MyScene.m

-(void)addMissile
{
    //initalizing spaceship node
    SKSpriteNode *missile;
    missile = [SKSpriteNode spriteNodeWithImageNamed:@"red-missile.png"];
    [missile setScale:0.15];

    //Adding SpriteKit physicsBody for collision detection
    missile.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:missile.size];
    missile.physicsBody.categoryBitMask = obstacleCategory;
    missile.physicsBody.dynamic = YES;
    missile.physicsBody.contactTestBitMask = shipCategory;
    missile.physicsBody.collisionBitMask = 0;
    missile.physicsBody.usesPreciseCollisionDetection = YES;
    missile.name = @"missile";
    //selecting random y position for missile
    int r = arc4random() % 300;
    missile.position = CGPointMake(self.frame.size.width + 20,r);
    [self addChild:missile];
}
For explanation of each line, take a look at addShip method. Once you have added this method add [self addMissile] at the end of initWithSize method and run to code to see our missile is appearing on the screen.
iOS Simulator Screen shot Nov 13, 2013 2.28.34 PM
Now we want to move the missile on the screen, so our spaceship can dodge it.
Add another constant for saving missile’s velocity right after background velocity.We want the missile to move little bit faster than background.
static const float BG_VELOCITY = 100.0;
static const float OBJECT_VELOCITY = 160.0;

Now we are going to add method to move the missile, at the end on MyScene.m

- (void)moveObstacle
{
    NSArray *nodes = self.children;//1

    for(SKNode * node in nodes){
        if (![node.name  isEqual: @"bg"] && ![node.name  isEqual: @"ship"]) {
            SKSpriteNode *ob = (SKSpriteNode *) node;
            CGPoint obVelocity = CGPointMake(-OBJECT_VELOCITY, 0); //2
            CGPoint amtToMove = CGPointMultiplyScalar(obVelocity,_dt); //3

            ob.position = CGPointAdd(ob.position, amtToMove); //4
            if(ob.position.x < -100)
            {
                [ob removeFromParent]; //5
            }
        }
    }
}
Let’s go through the code line by line.
  1. We collect all child nodes of the scene.
  2. Set the velocity by which the node is going to move
  3. Set the amount by which node has to move
  4. Set new position of the node
  5. We remove any node which has scrolled off the screen.
We going to call this method in update method like we called moveBg method. So now our update method looks like

-(void)update:(CFTimeInterval)currentTime {

    if (_lastUpdateTime)
    {
        _dt = currentTime - _lastUpdateTime;
    }
    else
    {
        _dt = 0;
    }
    _lastUpdateTime = currentTime;

    [self moveBg];
    [self moveObstacle];
}
Now we want to add missiles randomly at different y axis, every one second.
We are going to add another property to manage when was last time a missile was added on the screen.
    NSTimeInterval _lastMissileAdded;
We are going to use our update method to keep track of lastMissileAdded time interval.
-(void)update:(CFTimeInterval)currentTime {

    if (_lastUpdateTime)
    {
        _dt = currentTime - _lastUpdateTime;
    }
    else
    {
        _dt = 0;
    }
    _lastUpdateTime = currentTime;

    if( currentTime - _lastMissileAdded > 1)
    {
        _lastMissileAdded = currentTime + 1;
            [self addMissile];
    }

    [self moveBg];
    [self moveObstacle];

}
Run the project and you should be seeing multiple missiles on the screen now.
iOS Simulator Screen shot Nov 13, 2013 4.35.14 PM
Now we need to end the game if spaceship collides with the missile. To do that we need to add these two methods at the end of  MyScene.m


- (void)didBeginContact:(SKPhysicsContact *)contact
{
    SKPhysicsBody *firstBody, *secondBody;
    if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
    {
        firstBody = contact.bodyA;
        secondBody = contact.bodyB;
    }
    else
    {
        firstBody = contact.bodyB;
        secondBody = contact.bodyA;
    }

    if ((firstBody.categoryBitMask & shipCategory) != 0 &&
        (secondBody.categoryBitMask & obstacleCategory) != 0)
    {
            [ship removeFromParent];
    }
}

Since we set the scene as the contactDelegate of the physics world earlier, this method will be called whenever two physics bodies collide

There are two parts to this method:

  1. This method passes you the two bodies that collide, but does not guarantee that they are passed in any particular order. So this bit of code just arranges them so they are sorted by their category bit masks so you can make some assumptions later.
  2. Finally, it checks to see if the two bodies that collide are the spaceship and missile, and if so calls the method you wrote earlier.
If you run the current code, you will see if the spaceship collides with missile it will disappear.
Now, let’s create a new scene and layer that will serve as your “End of game” indicator. Create a new file with the iOS\Cocoa Touch\Objective-C class template, name the class GameOverScene, make it a subclass of SKScene, and click Next and then Create.
Then replace GameOverLayer.m with the following code:

#import "GameOverScene.h"
#import "MyScene.h"

@implementation GameOverScene
-(id)initWithSize:(CGSize)size {
    if (self = [super initWithSize:size]) {

        // 1
        self.backgroundColor = [SKColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];

        // 2
        NSString * message;
        message = @"Game Over";
        // 3
        SKLabelNode *label = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
        label.text = message;
        label.fontSize = 40;
        label.fontColor = [SKColor blackColor];
        label.position = CGPointMake(self.size.width/2, self.size.height/2);
        [self addChild:label];

        //4
        NSString * retrymessage;
        retrymessage = @"Replay Game";
        SKLabelNode *retryButton = [SKLabelNode labelNodeWithFontNamed:@"Chalkduster"];
        retryButton.text = retrymessage;
        retryButton.fontColor = [SKColor blackColor];
        retryButton.position = CGPointMake(self.size.width/2, 50);
        retryButton.name = @"retry";
        [self addChild:retryButton];

    }
    return self;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject]; 
    CGPoint location = [touch locationInNode:self];
    SKNode *node = [self nodeAtPoint:location]; //1

    if ([node.name isEqualToString:@"retry"]) { //2

        //3
        SKTransition *reveal = [SKTransition flipHorizontalWithDuration:0.5];
        MyScene * scene = [MyScene sceneWithSize:self.view.bounds.size];
        scene.scaleMode = SKSceneScaleModeAspectFill;
        [self.view presentScene:scene transition: reveal];

    }
}
@end

There are four parts to initWithSize method:

  1. Sets the background color to white, same as you did for the main scene.
  2. Sets the message to “Game Over”.
  3. Displays the label with Sprite Kit, choosing font and size.
  4. Creating another Sprite Kit label to represent our “Retry” button.
To track when user hit the replay button, we need touchesBegan method. This method is called when user touches anywhere on the screen. Let’s break down this method
  1. We track the node present at the location where user touched the screen.
  2. If the node touched name is equal to “retry”, then it means user has hit the replay button
  3. We transition back to MyScene to restart the game. You can pick from a variety of different animated transitions for how you want the scenes to display – we choose a flip transition here that takes 0.5 seconds.Then you create the scene you want to display, and use thepresentScene:transition: method on the self.view property.
Just one more thing to do before our game is ready to play.
In MyScene.m after removing the spaceship after collision we need to transition to GameOverScene. So replace didBeginContact with following code.

- (void)didBeginContact:(SKPhysicsContact *)contact
{
    SKPhysicsBody *firstBody, *secondBody;
    if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask)
    {
        firstBody = contact.bodyA;
        secondBody = contact.bodyB;
    }
    else
    {
        firstBody = contact.bodyB;
        secondBody = contact.bodyA;
    }

    if ((firstBody.categoryBitMask & shipCategory) != 0 &&
        (secondBody.categoryBitMask & obstacleCategory) != 0)
    {
        [ship removeFromParent];
        SKTransition *reveal = [SKTransition flipHorizontalWithDuration:0.5];
        SKScene * gameOverScene = [[GameOverScene alloc] initWithSize:self.size];
        [self.view presentScene:gameOverScene transition: reveal];

    }
}

Run the game and you should see Game over screen if you collide with a missile.

iOS Simulator Screen shot Nov 13, 2013 9.22.06 PM

And that’s a wrap! Here is the full source code for this Sprite Kit tutorial.

I hope you enjoyed this tutorial and are inspired to make your own game.

Advertisements

12 thoughts on “Simple Sprite Kit game tutorial- Part2

  1. It’s nice to find a tutorial that’s mostly code! I feel like I have a much better grasp of what’s going on here.

  2. Pingback: Simple Sprite Kit game tutorial- Part2 | Megha Gulati - appgong
  3. The following line shows an error ,

    SKScene * gameOverScene = [[GameOverScene alloc] initWithSize:self.size];

    Error:
    ../MyScene.m:205:37: Use of undeclared identifier ‘GameOverScene’; did you mean ‘gameOverScene’?

    ../MyScene.m:205:51: No visible @interface for ‘SKScene’ declares the selector ‘alloc’

  4. Pingback: Simple Sprite Kit game tutorial- Part1 | Megha Gulati
  5. in – (void)moveObstacle

    what should i do if i want the other nodes to be moved in the update except the background is this possible

    for example i create my background under -(id)initWithSize:(CGSize)size

    thanks in advanced

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s