我正在使用 spritekit 制作游戏。我在我的游戏中使用了一个操纵杆,它在一个名为“操纵杆”的单独 SKNode 类中声明。
在这个类中,我向类中的 View 添加了一个 UIGesturerecongiser。在构造方法中,其中一个参数是从游戏场景传来的 SKView。
Joystick 类中的构造方法:
init(colour: UIColor, position: CGPoint, skView: SKView) {
//constructor method
self.colour = colour;
self.parentposition = position;
self.view = skView;
super.init();
//setup properties
//user interaction is needed to allow touches to be detected
self.isUserInteractionEnabled = true;
//setup
setup();
}
在游戏场景中,我这样初始化类:
class GameScene: SKScene {
func setupJoyStick() {
let joystick1 = Joystick(colour: UIColor.red, position: CGPoint(x: screenwidth / 3, y: screenwidth / 10 * 1.5), skView: self.view!)
self.addChild(joystick1)
}
}
错误:
当我运行我的应用程序时,我收到一个错误,因为“self.view”返回 nil 并且因为它被强制解包,它导致了一个 fatal error 。
定义View的地方:
if let scene = GKScene(fileNamed: "GameScene") {
// Get the SKScene from the loaded GKScene
if let sceneNode = scene.rootNode as! GameScene? {
// Copy gameplay related content over to the scene
sceneNode.entities = scene.entities
sceneNode.graphs = scene.graphs
// Set the scale mode to scale to fit the window
sceneNode.scaleMode = .aspectFill
sceneNode.size = view.bounds.size
// Present the scene
if let view = self.view as! SKView? {
view.presentScene(sceneNode)
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
}
附加信息:
我正在使用:
- Xcode 9.2
- swift 4
- SpriteKit
我正在测试它:
- iPhone 6s
- 最新版本的 IOS(非测试版),最新公开发布。
有人可以解释为什么会发生这种情况以及如何解决这个问题。
在此先致谢,如有任何帮助,我们将不胜感激。
最佳答案
看起来您正在尝试获取 SKScene
的 view
属性,但它是零。这是因为你没有呈现 SKScene
。
关于ios - SpriteKit swift : SKView returning nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50545754/