问题描述
我想在我的主 GameScene 中添加一个 SKScene.SKReferenceNode 似乎是一个不错的解决方案.
I would like to add a SKScene to my main GameScene. SKReferenceNode seems to be a good solution.
我有:- GameScene.sks(主场景)- Countdown.sks(添加到 GameScene 的场景)- Countdown.swift(自定义类,如何初始化?SKScene?SKReferenceNode?SKNode)
I have :- GameScene.sks (main scene)- Countdown.sks (scene to add to GameScene)- Countdown.swift (Custom class, how does to init it? SKScene ? SKReferenceNode ? SKNode)
我不知道如何使用我的类 Countdown 以编程方式添加我的倒计时.
I don't know how to add programmatically my countdown using my class Countdown.
我试过了:
let path = Bundle.main.path(forResource: "Countdown", ofType: "sks")
let cd = SKReferenceNode (url: NSURL (fileURLWithPath: path!) as URL) as! Countdown
cd.name = "countdown"
self.addChild(cd)
但我有以下错误:
Could not cast value of type 'SKReferenceNode' (0x10d97ad88) to 'LYT.Countdown' (0x10a5709d0
我还尝试了一些更简单的方法,例如:
I also tried something more simple like:
let cd=Countdown(scene:self)
self.addChild(cd)
但我不知道如何使用 Countdown.sks 文件初始化类.
But I don't know how to init the class using the Countdown.sks file.
我知道我也有可能创建一个 SKNode 类,并以编程方式 100% 初始化它,但使用关联的 .sks 文件以使用 Xcode 场景编辑器对我来说非常重要.
I know I also have the possibility to create a SKNode class, and init it 100% programmatically, but it really important for me to use the associated .sks file in order to use the Xcode scene editor.
推荐答案
我这样做了,我不知道是否是最好的方法,但是可行:
I do that, I don't know if is the best way to do this, but works:
我有 2 个文件 Dragon.swift 和 sks
I've 2 file Dragon.swift and sks
我添加了一个主"节点,例如 DragonNode 和其他节点子节点
I've added a "main" node like DragonNode and other node children of this
现在,DragonNode 是一个自定义类,在 sks 文件中设置它:
Now, the DragonNode is a custom class, set it in sks file:
DragonNode 是一个普通的 SKSpriteNode
The DragonNode is a normal SKSpriteNode
class DragonNode: SKSpriteNode, Fly, Fire {
var head: SKSpriteNode!
var body: SKSpriteNode!
var shadow: SKSpriteNode!
var dragonVelocity: CGFloat = 250
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//Example other node from sks file
body = self.childNodeWithName("Body") as! SKSpriteNode
head = body.childNodeWithName("Head") as! SKSpriteNode
shadow = self.childNodeWithName("Shadow") as! SKSpriteNode
shadow.name = "shadow"
}
//Dragon Func
func fireAction () {}
func flyAction () {}
}
在场景中,添加一个 SKReferenceNode:
Inside the scene, add a SKReferenceNode:
在 SKScene 代码中:
In the SKScene code:
let dragonReference = self.childNodeWithName("DragonReference") as! SKReferenceNode
let dragonNode = dragonReference.getBasedChildNode() as! DragonNode
print(dragonNode)
//Now you can use the Dragon func
dragonNode.flyAction()
getBasedChildNode()
是查找基于节点的扩展(第一个)
getBasedChildNode()
is an extension to find your based node (the first one)
extension SKReferenceNode {
func getBasedChildNode () -> SKNode? {
if let child = self.children.first?.children.first {return child}
else {return nil}
}
}
这篇关于将 SKReferenceNode/SKScene 添加到 SpriteKit 中的另一个 SKScene的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!