在Swift中使用Sprite Kit呈现场景

时间:2017-01-25 18:30:32

标签: swift xcode sprite-kit

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

startActivityForResult(new Intent(getActivity(), ActivityA.class), REQUEST_CODE)

和相同以显示你死的主菜单,它完全正常,但由于某种原因,当我尝试从主菜单中呈现GameScene时它不起作用

1 个答案:

答案 0 :(得分:0)

我认为除了你向我们展示的内容之外,还有一个错误。我可以创建一个非常基本的项目,从MenuScene(由GameViewController定向)开始,当你点击MenuScene上的任何地方时,它会带你到GameScene。在GameScene中,如果单击绿色框,则会返回到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)
            }
        }
    }
}