0

I'm trying to fetch all children (identified by a name) of a GameScene in order to rotate some SKSpriteNode synchronously with the device.

For the moment I have this code:

override func update(currentTime: CFTimeInterval) {  
    if manager.deviceMotionAvailable {
        manager.deviceMotionUpdateInterval = 0.01
        manager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue()) {  
            [weak self] (data: CMDeviceMotion!, error: NSError!) in
            let rotation = atan2(data.gravity.x, data.gravity.y) - M_PI  

            for (var i = 1 ; i < self?.children.count ; i++){  
                var child = ???   // How can I get the child i
                if (child.name == 'Monster'){
                    let action = SKAction.rotateByAngle(CGFloat(DegreesToRadians(rotation)), duration:0)
                    child.runAction(action)
                }
            }
        }
    }
}  

How can I get the child i? Is it the good way to do it? Otherwise, I can handle an array list with all my children added to the GameScene...

Bogy
  • 944
  • 14
  • 30

1 Answers1

3

In swift you can enumerate through all child nodes with a specific name using the following method:

enumerateChildNodesWithName("Monster", usingBlock: {
     let action = SKAction.rotateByAngle(CGFloat(DegreesToRadians(rotation)), duration:0)
                child.runAction(action)
}

Documentation: https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKNode_Ref/index.html#//apple_ref/occ/instm/SKNode/enumerateChildNodesWithName:usingBlock:

chrissukhram
  • 2,957
  • 1
  • 13
  • 13
  • Perfect! Thank you :) I also use this link http://stackoverflow.com/questions/24213436/how-to-use-enumeratechildnodeswithname-with-swift-in-spritekit to use enumerateChildNodesWithName correctly. – Bogy Apr 01 '15 at 23:14