【问题标题】:Change properties for children of SKNode in a for loop在 for 循环中更改 SKNode 子级的属性
【发布时间】:2015-02-01 04:11:41
【问题描述】:
我了解 SKNode 的 children 属性是只读属性。不过,有没有办法在迭代孩子时,可以改变这些孩子的属性?
例如:
let background = SKSpriteNode(imageNamed: "Background.jpg")
for child in background.children{
child.position = CGPoint(x: 0, y: 0)
}
【问题讨论】:
标签:
swift
for-loop
sprite-kit
sknode
【解决方案1】:
您可以将孩子投射到SKNode,然后更改位置。
for child in self.children {
if let sprite = child as? SKNode {
sprite.position = CGPoint(x: 0, y: 0)
}
}
【解决方案2】:
children 属性是只读的,因此您不能使用此属性添加或删除元素(子元素)(有特定的方法可以做到)。
但是您可以修改 background.children 中元素的某些属性。
for child in background.children as [SKNode] {
child.position = CGPoint(x: 0, y: 0)
}
将 background.children 转换为 [SKNode] 是安全的,并由 documentation 保证。