以编程方式完成时,SpriteKit中没有任何内容加载到屏幕

时间:2018-04-21 13:25:35

标签: ios swift sprite-kit

我无法弄清楚为什么这不会起作用,并且看起来好像场景正在改变,因为背景颜色不会变为红色。这是我的代码:

GameViewController.swift

class GameViewController: UIViewController {

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        let skView = self.view as! SKView
        if skView.scene == nil {

            // Set options
            skView.ignoresSiblingOrder = true
            skView.showsFPS = true
            skView.showsNodeCount = true
            skView.showsPhysics = true

            // Create a scene
            let gameScene = SKScene(size: skView.bounds.size)

            // Set the scale mode to scale to fit the window
            gameScene.scaleMode = .aspectFill

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

    override var shouldAutorotate: Bool {
        return true
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        if UIDevice.current.userInterfaceIdiom == .phone {
            return .allButUpsideDown
        } else {
            return .all
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Release any cached data, images, etc that aren't in use.
    }

    override var prefersStatusBarHidden: Bool {
        return true
    }
}

GameScene.swift

class GameScene: SKScene {

    // Create objects
    var player = SKSpriteNode()

    // Initialize
    override init(size: CGSize) {
        super.init(size: size)

        //Other init code
        player.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
        player.setScale(0.5) 
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func didMove(to view: SKView) {
        self.backgroundColor = UIColor.red
        self.addChild(player)  
    }  
}

屏幕上没有任何内容,它只是黑色/灰色。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您的代码中没有指定要打开GameScene的位置。

// Create a scene
let gameScene = SKScene(size: skView.bounds.size)

如果您没有在场景编辑器中创建相应的SKS文件,而是希望加载在代码中使用创建的场景......

应该是什么......

// Create a scene
let gameScene = GameScene(size: skView.bounds.size)