Book Image

Game Development with Swift

By : Stephen Haney
Book Image

Game Development with Swift

By: Stephen Haney

Overview of this book

Table of Contents (18 chapters)
Game Development with Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Collecting coins


As a main goal for the player, collecting coins should be one of the most enjoyable aspects of our game. We will create a rewarding animation when the player contacts a coin. Follow these steps to implement coin collection:

  1. In GameScene.swift, add a new property to the GameScene class:

    var coinsCollected = 0
  2. In Coin.swift, add a new function to the Coin class named collect:

    func collect() {
        // Prevent further contact:
        self.physicsBody?.categoryBitMask = 0
        // Fade out, move up, and scale up the coin:
        let collectAnimation = SKAction.group([
            SKAction.fadeAlphaTo(0, duration: 0.2),
            SKAction.scaleTo(1.5, duration: 0.2),
            SKAction.moveBy(CGVector(dx: 0, dy: 25), duration: 0.2)
        ])
        // After fading it out, move the coin out of the way
        // and reset it to initial values until the encounter
        // system re-uses it:
        let resetAfterCollected = SKAction.runBlock {
            self.position.y = 5000
            self.alpha = 1
            self.xScale...