从子类加载 Spritekit 场景
Load Spritekit scene from a subclass
我有一个 SKScene 的子类,我想在其中从 .sks
文件加载场景。我必须使用 super.init(size: CGSize)
在子类的初始化中初始化 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 中有一个自定义 class。你只要把 "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.
}
如果您决定从文件加载,则没有理由再次初始化。您可以通过覆盖以下内容来添加初始化函数:
override func sceneDidLoad() {
} //called after .sks is loaded.
override func didMove(to view: SKView) {
//change the size here.
} // called after presentation.
我有一个 SKScene 的子类,我想在其中从 .sks
文件加载场景。我必须使用 super.init(size: CGSize)
在子类的初始化中初始化 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 中有一个自定义 class。你只要把 "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.
}
如果您决定从文件加载,则没有理由再次初始化。您可以通过覆盖以下内容来添加初始化函数:
override func sceneDidLoad() {
} //called after .sks is loaded.
override func didMove(to view: SKView) {
//change the size here.
} // called after presentation.