How to properly switch SKScenes to SpriteKit with Swift?

I am developing a game with three different SKScenes (scene1, scene2, scene3). In GameViewController, I initialize all of them as follows:

class GameViewController: UIViewController {
  var hero = Hero()
  var skView: SKView!

  var scene1: SKScene!
  var scene2: SKScene!
  var scene3: SKScene!

  override func viewDidLoad() {
    super.viewDidLoad()

    // init scenes
    scene1 = SKScene(size: view.bounds.size, hero: hero)
    scene2 = SKScene(size: view.bounds.size, hero: hero)
    scene3 = SKScene(size: view.bounds.size, hero: hero)

    scene1.scaleMode = .AspectFill
    scene2.scaleMode = .AspectFill
    scene3.scaleMode = .AspectFill

    // set view
    skView = self.view as SKView

    // present the first scene
    skView.presentScene(scene1)
}

My idea is to present the first scene first and present (swith to) another scene later (i.e. when the hero is stronger). In each scene, the sprite hero was added like this:

  func addHero() {
    let heroSprite = SKSpriteNode(imageNamed: "hero")
    hero.sprite = heroSprite
    heroSprite.position = CGPoint(x: size.width/4, y: size.height/2)
    addChild(heroSprite)
  }

And in the update method, the position of the hero is updated by touch.

func update() {
  if touching {
    hero.position++
  }
}

Hero class is as follows:

class Hero {
  var sprite: SKSpriteNode?
}

Problem : The hero moves, touching, when the first scene is just initialized (scene1). This means that the hero is no longer moving with the code above.

Can someone give me advice on what I did wrong? Thanks in advance!

PS: full codes can be found on Github .

+4
1

: SpriteKit Swift?

, , init. , "didMoveToView", "init" "setup":

if isInit {
  do nothing
} else {
  add sprites
  isInit = true
}
0

All Articles