Book Image

Swift by Example

By : Giordano Scalzo
Book Image

Swift by Example

By: Giordano Scalzo

Overview of this book

Table of Contents (15 chapters)

A flying bird


It's now the time to implement our hero.

Adding the Bird node

First of all, we must add a new character to GameScene:

class GameScene: SKScene {
    private var bird: Bird!
    //...
    override func didMoveToView(view: SKView) {
        //...
        bird = Bird(textureNames: ["bird1.png", "bird2.png"]).addTo(screenNode)
        bird.position = CGPointMake(30.0, 400.0)

        actors = [sky, city, ground, bird]
        //...
    }
}

We can see that this new class behaves like the other, which we have already implemented:

import SpriteKit

class Bird : Startable {
    private var node: SKSpriteNode!
    private let textureNames: [String]
    
    var position : CGPoint {
        set { node.position = newValue }
        get { return node.position }
    }
    
    init(textureNames: [String]) {
        self.textureNames = textureNames
        node = createNode()
    }
    
    func addTo(scene: SKSpriteNode) -> Bird{
        scene.addChild(node)
        return self
    }
}

In...