【问题标题】:Calling a func of GameViewController from GameScene从 GameScene 调用 GameViewController 的函数
【发布时间】:2018-07-18 10:22:59
【问题描述】:

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

我现在尝试了很多不同的东西,例如:LINK(我多次尝试每个答案,但仍然无法正常工作)

但不管我尝试了什么,它甚至都不会调用函数。

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

代码: 游戏视图控制器:

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
        })
    }
}

游戏场景:

class GameScene: SKScene, SKPhysicsContactDelegate {

   ...

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

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

  }
}

【问题讨论】:

    标签: ios swift4 xcode9


    【解决方案1】:

    选项 1:

    当你第一次从GameViewController 调用GameScene 时,你应该传递GameViewController 实例,然后把这个实例保存在一些var gameVC: GameViewController! 中并像你在准备segue 方法中一样初始化它。

    然后你就可以拨打gameVC.GameOver()

    选项 2:

    当你想打电话给GameOver()时,把这个放在GameScene中:

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

    【讨论】:

    • 这不是和链接的第一个答案一样吗?因为我不知道为什么,但是这个解决方案根本不起作用?
    • 哦,是的,我没有看到这个链接......你能用GameViewController的终点和GameScene的输入点编辑你的问题吗?提供更多信息?
    • 游戏视图控制器的终点?你的意思是当我开始游戏场景时,它像往常一样在视图中加载。所以游戏立即开始,在游戏场景结束时,当两个对象发生碰撞时,我只需删除所有节点,然后从游戏视图控制器中出现一个按钮。对不起,如果我理解错了,我的英语不是那么好
    • 我的意思是当你在GameViewController 中调用GameScene 时,比如执行segue。
    • 是的,就像我说的那样,我在视图中调用游戏场景确实加载了
    猜你喜欢
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多