由於Sprite Kit提供了訪問場景節點樹中精靈的簡便方法,幾乎沒有理由使用數組來管理精靈節點。在這種情況下,您可以添加一組精靈SKNode
,因爲您可以輕鬆訪問精靈與node = sprite.parent
中的「容器」。然後你可以遍歷node.children
遍歷該容器中的精靈。這裏有一個如何做一個例子:
var selectedNode:SKSpriteNode?
override func didMoveToView(view: SKView) {
scaleMode = .ResizeFill
let width = view.frame.size.width
let height = view.frame.size.height
let colors = [SKColor.redColor(), SKColor.greenColor(), SKColor.blueColor()]
// Create 3 container nodes
for i in 1...3 {
let node = SKNode()
// Create 5 sprites
for j in 1...5 {
let sprite = SKSpriteNode(imageNamed:"Spaceship")
sprite.color = colors[i-1]
sprite.colorBlendFactor = 0.5
sprite.xScale = 0.125
sprite.yScale = 0.125
// Random location
let x = CGFloat(arc4random_uniform(UInt32(width)))
let y = CGFloat(arc4random_uniform(UInt32(height)))
sprite.position = CGPointMake(x, y)
// Add the sprite to a container
node.addChild(sprite)
}
// Add the container to the scene
addChild(node)
}
}
選擇一個精靈在touchesBegan
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
let node = nodeAtPoint(location)
selectedNode = node as? SKSpriteNode
}
}
移動將所選的精靈
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch in (touches as! Set<UITouch>) {
let location = touch.locationInNode(self)
selectedNode?.position = location
}
}
旋轉所有的孩子在節點包含精選精靈
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
if let parent = selectedNode?.parent?.children {
for child in parent {
let action = SKAction.rotateByAngle(CGFloat(M_PI*2.0), duration: 2.0)
child.runAction(action)
}
}
selectedNode = nil
}
那很好。 =)它是獲得一組節點的一種巧妙方式。多謝! – Gusfat