gkolman gkolman - 4 months ago 20
Swift Question

How to change the first SKscene that is presented through gameviewcontroller

error message

So i have created a couple of different SKScenes in my swift project and I've seen on a couple tutorials that you don't have to launch you gameScene.swift as your first scene, however i can not find a tutorial that explains how

import UIKit
import SpriteKit

class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true

/* Sprite Kit applies additional optimizations to improve
rendering performance */
skView.ignoresSiblingOrder = true

/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill

skView.presentScene(scene)
}
}
}


Im trying to change the GameScene SKS to my MainMenu SKS, but i keep getting errors and I'm definitely missing something. Can anyone help me out?

Answer
import UIKit
import SpriteKit

class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

if let newScene = MenuScene(fileNamed:"MenuScene") {
    // Configure the view.
    let skView = self.view as! SKView
    skView.showsFPS = true
    skView.showsNodeCount = true

    /* Sprite Kit applies additional optimizations to improve 
    rendering performance */
    skView.ignoresSiblingOrder = true

    /* Set the scale mode to scale to fit the window */
    newScene.scaleMode = .AspectFill

    skView.presentScene(newScene)
}
}
} 

So instead of having GameScene as your initial scene, just create MenuScene instance and present it in your viewDidLoad. Note that you have to create coresponding MenuScene.sks file because of this line:

If let newScene = MenuScene(fileNamed:"MenuScene.sks"){ //...}

because you are loading it from a file.

Also to transition to another scene, use following pattern and for example in touchesBegan create new scene, optionally create SKTransition and present the new scene.

Comments