我正在使用Swift和Sprite Kit。我有SKNode
名为MrNode
,其中包含多个SKSpriteNodes
和SKNode
个子节点。有些SKNode
的孩子也有自己的孩子。要引用它们,我会执行以下操作
var MrNode = SKNode?()
override func didMoveToView(view: SKView)
{
MrNode = childNodeWithName("MrNode")
}
func DimLights()
{
let liftmotor1:SKNode = MrNode!.childNodeWithName("LiftMotor1")!
let liftPlatform1:SKSpriteNode = liftmotor1.childNodeWithName("LiftPlatform")as! SKSpriteNode
let light1:SKSpriteNode = liftPlatform1.childNodeWithName("light1")as! SKSpriteNode
let light2:SKSpriteNode = liftPlatform1.childNodeWithName("light2")as! SKSpriteNode
light1.alpha = 0.2
light1.alpha = 0.2
}
要查找孩子的孩子的孩子的SKSpriteNodes
,请致电DimLights()
。这是最好的方法吗?还是有更好的东西?
答案 0 :(得分:0)
是的,Sprite Kit访问子节点的目的是通过name
(你的方式)或者使用for循环来检查子节点的childNodeWithName()
属性通过节点的children
数组。
您也可以直接在类中声明变量:
class exampleClass {
var property: SKSpriteNode
}
此属性对整个类都是可见的,因此您可以从类方法中访问它。但是,如果您有很多这些,那么您会注意到代码很快变得混乱。
答案 1 :(得分:0)
如果您需要经常访问light1
和light2
,可以在几个weak properties
中保存对它们的引用。
我认为mrNode
,light1
和light2
将始终存在,因此我将属性声明为implicitly unwrapped
。
我还声明了它们weak
,因为相关节点将通过父节点的引用保持活动状态。但是,将它们声明为week
并不是必需的。
我尽快(在didMoveToView
内)调用populateProperties
。
此方法使用可选绑定技术来查找节点。如果IF失败,则打印错误消息。但是,如果节点始终存在于场景中,则不会发生这种情况。
最后在dimLights
内,您可以使用相关的实例属性轻松访问您的节点。
class MyScene : SKScene {
weak var mrNode: SKNode!
weak var light1: SKSpriteNode!
weak var light2: SKSpriteNode!
override func didMoveToView(view: SKView) {
super.didMoveToView(view)
populateProperties()
}
func dimLights() {
light1.alpha = 0.2
light2.alpha = 0.2
}
private func populateProperties() {
if let
mrNode = childNodeWithName("MrNode"),
liftmotor1 = mrNode.childNodeWithName("LiftMotor1"),
liftPlatform1 = liftmotor1.childNodeWithName("LiftPlatform"),
light1 = liftPlatform1.childNodeWithName("light1") as? SKSpriteNode,
light2 = liftPlatform1.childNodeWithName("light2") as? SKSpriteNode {
self.mrNode = mrNode
self.light1 = light1
self.light2 = light2
} else {
debugPrintln("Error when populating properties")
}
}
}