How to move from view controller to skscene

谁都会走 提交于 2019-12-13 03:48:19

问题


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 ?


回答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.



来源:https://stackoverflow.com/questions/48962880/how-to-move-from-view-controller-to-skscene

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!