我正在使用 Swift 和 Sprite Kit。我有一个名为 MrNode
của SKNode
,它有多个 SKSpriteNodes
Và 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()
。这是最好的方法还是有更好的方法?
如果您需要频繁访问 light1
Và light2
,您可以在几个弱属性
中保存对它们的引用。
我假设 mrNode
、light1
Và light2
将始终存在,因此我将属性声明为隐式解包
.
我还声明它们弱
,因为相关节点将通过父节点的引用保持事件状态。然而,没有必要将它们声明为week
。
我尽快(在 didMoveToView
内)调用了 populateProperties
。
此方法使用可选绑定(bind)技术来查找节点。如果 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
} khác {
debugPrintln("Error when populating properties")
}
}
}
Tôi là một lập trình viên xuất sắc, rất giỏi!