0

I want to present SKScene from a UIViewController in swift language, I'm developing a game in iOS , the menu is a UIViewController and the game is in SpriteKit, I need to move from the menu (UIViewController) to the game (SKScene) upon pressing a button. How can I do something like that ?

Enrique Bermúdez
  • 1,740
  • 2
  • 11
  • 25
  • just create a "game" using the Xcode template, it automatically includes the transition from UIGameViewController (UIViewController) to GamesScene (SKScene) – Ron Myschuk Feb 24 '18 at 14:28
  • I already tried it, i have this scenario: first i enter the game (skscene) then button moves to viewcontroller then i want to move to another skscene from the controller – Ahed Krakra Feb 24 '18 at 14:49
  • You should construct your question with all of the information of of the start, and not make people have to guess at your scenario. Why are you constructing your menu in UIKit? why not just do it in SpriteKit?Regardless it's the same technique to transition to the second scene as it is to transition to the first – Ron Myschuk Feb 24 '18 at 15:24

1 Answers1

1

Like @Ron Myschuk said you should consider moving your menu to SpriteKit. If you want to use UIKit you will need to communicate the SKScene with the UIViewController (I guess that is your problem).

You can achieve this with the delegate pattern.

Using this pattern your code might look something like this:

/// Game actions that should be notified.
Protocol GameSceneDelegate: class {
    func gameDidEnd()
}

public class GameScene: SKScene {

    weak var gameDelegate: GameSceneDelegate?

    // MARK: - Menu Actions
    func userDidPressMenuButton() {
        ///Do what you want to do..
    }
}

class GameViewController: UIViewController, GameSceneDelegate{

    var scene: GameScene?

    override func viewDidLoad() {

        if (self.view as! SKView?) != nil {
            self.scene = GameScene(fileNamed: "GameScene")
        }

        self.scene?.gameDelegate = self
    }

    // MARK: - GameSceneDelegate methods

    func gameDidEnd(){
        ///Do what you want to do..
    }

    // MARK: - Actions
    @IBAction func pressMenuButtonAction(_ sender: Any) {

        self.scene?.userDidPressMenuButton()
    }
}

When a button is pressed in your UIViewController you call the SKScene to do what ever it needs to do. And when the scene needs to tell the menu a relevant action (like game finish) it calls its delegate, that is your UIViewController.

Enrique Bermúdez
  • 1,740
  • 2
  • 11
  • 25