0
votes

I have a game where I have two scenes: FarmScene and WoodScene. Each scene has a .SKS file and a .swift file - one to design, and one to code. I've managed to move from FarmScene to WoodScene like this:

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    for touch in touches {
        let location = touch.location(in: self)
        let node : SKNode = self.atPoint(location)
        if node.name == "WoodIcon" {
            if let view = self.view as! SKView? {
                // Load the SKScene from 'GameScene.sks'
                if let scene = SKScene(fileNamed: "WoodScene") {
                    // Set the scale mode to scale to fit the window
                    scene.scaleMode = .aspectFill

                    // Present the scene
                    view.presentScene(scene)
                }
            }
        }
    }
}

In my previous games I've used a SKTransition to move to different scenes, and with that I could do some cool transitions like flip, fade and push.

I was wondering if this is the "correct" way of changing scenes when using the scene designer in Xcode? Or maybe I'm missing something.

Looking forward to hear from you.

1

1 Answers

1
votes

I wouldn't do it like that with a loop, just to keep yourself from potentially running that presentation code more than once. Maybe setup your touchesBegan method with a guard statement

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    // Guard to just use the first touch
    guard let touch = touches.first else { return }
    let location = touch.location(in: self)
    let node : SKNode = self.atPoint(location)
    if node.name == "WoodIcon" {
        if let view = self.view as! SKView? {
            // Load the SKScene from 'GameScene.sks'
            if let scene = SKScene(fileNamed: "WoodScene") {
                // Set the scale mode to scale to fit the window
                scene.scaleMode = .aspectFill

                // Present the scene
                view.presentScene(scene)
            }
        }
    }
}

Also if you want to do a custom transition through code you can do something like this:

func customTransition() {

    // Wait three seconds then present a custom scene transition
    let wait = SKAction.wait(forDuration: 3.0)
    let block = SKAction.run {

        // Obviously use whatever scene you want, this is just a regular GameScene file with a size initializer
        let newScene = SKScene(fileNamed: "fileName")!
        newScene.scaleMode = .aspectFill
        let transitionAction = SKTransition.flipHorizontal(withDuration: 0.5)
        self.view?.presentScene(newScene, transition: transitionAction)

    }
    self.run(SKAction.sequence([wait, block]))

}

I wouldn't say there is a right or wrong way, just preference about how fancy you want the transition to look.