因此,当我开始我的游戏时,你可以一直玩到你死,然后主菜单场景出现,如果你触摸主菜单中的屏幕,你应该再次加载游戏场景,但我得到一个错误,我使用此代码来呈现游戏场景:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let revealGameScene = SKTransition.fade(withDuration: 0.5)
    let goToGameScene = GameScene(size: self.size)
    goToGameScene.scaleMode = SKSceneScaleMode.aspectFill
    self.view?.presentScene(goToGameScene, transition:revealGameScene)
}

同样,当你死后也会出现主菜单,这很好,但由于某些原因,当我试图从主菜单中出现游戏场景时,它就不起作用了

最佳答案

我认为你给我们看的东西一定有错误。我可以创建一个非常基本的项目,从MenuScene开始(由GameViewController指导),当你点击MenuScene上的任何地方,它会带你进入游戏场景。在游戏场景中,如果你点击一个绿色框,它会带你回到菜单。一圈又一圈你走。
看一下代码,看看是否与您的代码有什么不同

class GameViewController: UIViewController {

    var menuScene: MenuScene!
    var skView: SKView!

    override func viewDidLoad() {

        super.viewDidLoad()

        // Create and configure the scene.
        skView = self.view as! SKView

        menuScene = MenuScene(size: skView.bounds.size)
        menuScene.scaleMode = .aspectFill

        skView.ignoresSiblingOrder = true

        skView.showsFPS = true
        skView.showsNodeCount = true


        // Present the scene.
        skView.presentScene(menuScene)
    }
}

class MenuScene: SKScene {

    override init(size: CGSize) {

        super.init(size: size)

        self.anchorPoint = CGPoint(x: 0.5, y: 0.5)
        let background = SKSpriteNode(color: .red, size: self.size)
        background.position = CGPoint(x: 0, y: 0)
        addChild(background)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        let revealGameScene = SKTransition.fade(withDuration: 0.5)
        let goToGameScene = GameScene(size: self.size)
        goToGameScene.scaleMode = SKSceneScaleMode.aspectFill
        self.view?.presentScene(goToGameScene, transition:revealGameScene)
    }
}


class GameScene: SKScene {

    private var box = SKSpriteNode()

    override func didMove(to view: SKView) {

        box = SKSpriteNode(color: .green, size: CGSize(width: 200, height: 200))
        box.position = CGPoint.zero
        addChild(box)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

       if let touch = touches.first as UITouch! {

            let touchLocation = touch.location(in: self)

            if box.frame.contains(touchLocation) {

                let revealGameScene = SKTransition.fade(withDuration: 0.5)
                let goToMenuScene = MenuScene(size: self.size)
                goToMenuScene.scaleMode = SKSceneScaleMode.aspectFill
                self.view?.presentScene(goToMenuScene, transition:revealGameScene)
            }
        }
    }
}

关于swift - Swift中Sprite Kit的当前场景,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41858967/

10-14 23:29