gpt4 book ai didi

swift - Swift 中的 Sprite Kit Child of Child of Child

转载 作者:行者123 更新时间:2023-11-30 14:10:09 28 4
gpt4 key购买 nike

我正在使用 Swift 和 Sprite Kit。我有一个名为 MrNodeSKNode,它有多个 SKSpriteNodesSKNode 子节点。一些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()。这是最好的方法还是有更好的方法?

最佳答案

如果您需要频繁访问 light1light2,您可以在几个弱属性中保存对它们的引用。

我假设 mrNodelight1light2 将始终存在,因此我将属性声明为隐式解包 .

我还声明它们,因为相关节点将通过父节点的引用保持事件状态。然而,没有必要将它们声明为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
} else {
debugPrintln("Error when populating properties")
}
}
}

关于swift - Swift 中的 Sprite Kit Child of Child of Child,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31863323/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com