从子类加载Spritekit场景

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (9)

我有一个SKScene的子类,我想从.sksFile 加载一个场景。我必须使用super.init(size: CGSize)在我的子类的init中初始化SKScene而不是super.init(fileNamed: String),因为它super.init(fileNamed: String)不是指定的初始化器。如何将SKScene子类化并使用语义super.init(fileNamed: String)从文件加载场景?

import SpriteKit

class Spielfeld: SKScene {

    var x: Int     // Anzahl Felder in x-Richtung
    var y: Int     // Anzahl Felder in y-Richtung
    var up: SKSpriteNode = SKSpriteNode()
    var down: SKSpriteNode = SKSpriteNode()
    var left: SKSpriteNode = SKSpriteNode()
    var right: SKSpriteNode = SKSpriteNode()

    init(_ x: Int, _ y: Int, fileNamed: String, size: CGSize) {
        self.x = x
        self.y = y
        super.init(size: size)
        up = self.childNode(withName: "Up") as! SKSpriteNode
        down = self.childNode(withName: "Down") as! SKSpriteNode
        left = self.childNode(withName: "Left") as! SKSpriteNode
        right = self.childNode(withName: "Right") as! SKSpriteNode
    }

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

}
提问于
用户回答回答于

没有必要,因为.sks中有一个自定义类。你只需把“Spielfeld”放进去。

然后在viewController中:

if let sceneNode = SKScene.init(fileNamed: "Spielfeld(Whatever your name is here)") { 
         (sceneNode as! Spielfeld).property = "anyValueToUse"

         if let view = self.view as! SKView? {
            view.presentScene(sceneNode) //present the scene.
   }

如果您决定从文件加载,则没有理由再次初始化。您可以通过覆盖以下内容来添加init函数:

   override func sceneDidLoad() {  
     } //called after .sks is loaded.

override func didMove(to view: SKView) {
//change the size here.
 } // called after presentation.

扫码关注云+社区

领取腾讯云代金券