从GameScene调用GameViewController函数

时间:2018-07-18 10:22:59

标签: ios swift4 xcode9

我想从GameScene调用GameViewController的函数。 ->如果游戏结束,我想调用GameViewController()。GameOver()

我现在尝试了许多类似的尝试:LINK(我多次尝试了每个答案,但仍然没有效果)

但是不管我尝试了什么,它甚至都没有称为func。

希望任何人都可以帮助我。

代码: GameViewController:

class GameViewController: UIViewController {

    @IBOutlet weak var Button: UIButton!

    override func viewDidLoad() {
    super.viewDidLoad()
        if let view = self.view as! SKView? {
        // Load the SKScene from 'GameScene.sks'
        if let scene = GameScene(fileNamed: "GameScene") {
            // Set the scale mode to scale to fit the window
                if UIDevice().userInterfaceIdiom == .phone {
                    scene.scaleMode = .aspectFill
                }else{
                    scene.scaleMode = .aspectFit
                }


            // Present the scene
            view.presentScene(scene)

            skView = view



        }

        view.ignoresSiblingOrder = true

        view.showsFPS = false
        view.showsNodeCount = false


    }

     ... 
    @IBAction func Button(_ sender: Any) {

    animation()



         if let gameScene = skView.scene as? GameScene { // check to see if the current scene is the game scene
             gameScene.start()
         }
    }

func animation(){
    UIButton.animate(withDuration: 1, animations: {
        self.Button?.alpha = 0
    })
}

    func GameOver(){
        UIButton.animate(withDuration: 1, animations: {
            self.Button?.alpha = 1
        })
    }
}

GameScene:

class GameScene: SKScene, SKPhysicsContactDelegate {

   ...

   func torpedoDidCollideWithAlien (torpedoNode:SKSpriteNode, alienNode:SKSpriteNode) {

     GameViewController().GameOver()
     removeAllActions()
     removeAllChildren()

  }
}

1 个答案:

答案 0 :(得分:0)

选项1:

第一次从GameViewController调用GameScene时,您应该传递GameViewController实例,然后将该实例保存在某个var gameVC: GameViewController!中,然后像您一样对其进行初始化准备segue方法。

然后您就可以致电gameVC.GameOver()

选项2:

当您要呼叫GameScene时,将其放在GameOver()中:

if let controller = self.view?.window?.rootViewController as? GameViewController {
   controller.GameOver()
}