问题描述
我想在我的主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}
}
}
这篇关于在SpriteKit中将SKReferenceNode/SKScene添加到另一个SKScene的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!