在GameViewController

时间:2017-05-10 15:18:12

标签: swift sprite-kit

想要在游戏开始前预加载textureAtlases,所以我决定将场景入门代码放入完成处理程序,但由于某种原因应用程序崩溃。这是我的代码:

import UIKit
import SpriteKit
import GameplayKit

class GameViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let gpuAtlas = SKTextureAtlas(named: "GP")
        let ppAtlas = SKTextureAtlas(named: "PP")

        SKTextureAtlas.preloadTextureAtlases([gpuAtlas, ppAtlas]) {

            if let view = self.view as? SKView {

                let scene = GameScene(size: self.view.bounds.size)
                // Set the scale mode to scale to fit the window
                scene.scaleMode = .aspectFill

                // Present the scene
                view.presentScene(scene)


                view.ignoresSiblingOrder = true

                view.showsFPS = true
                view.showsNodeCount = true
            }
        } 
    }

    override var shouldAutorotate: Bool {
        return true
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }

    override var prefersStatusBarHidden: Bool {
        return true
    }
}

如果我删除preload纹理图集方法,一切都会正常工作,但我希望预加载纹理有一个更改,以摆脱第一个关键帧冻结,因为在缓存中加载纹理。

错误:

  

致命错误:在解包可选值时意外发现nil

更新: 它在方法didSimulatePhysics中的GameScene.swift文件中崩溃。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

尝试此操作(使用main thread进行视图操作和weak self):

SKTextureAtlas.preloadTextureAtlases([gpuAtlas, ppAtlas]) { [weak self] in
    guard let gameView = self?.view as? SKView else { return }
    DispatchQueue.main.async {
        let scene = GameScene(size: gameView.bounds.size)
        // Set the scale mode to scale to fit the window
        scene.scaleMode = .aspectFill
        // Present the scene
        gameView.presentScene(scene)
        gameView.ignoresSiblingOrder = true
        gameView.showsFPS = true
        gameView.showsNodeCount = true
    }
}

您是否检查scene是否可选?如果是这样的话:

guard let scene = GameScene(size: gameView.bounds.size) else { return }

答案 1 :(得分:0)

JSP

不应该编译 - 变量名为gpuAtlas和ppAtlas而不是GP和PP。