获取GameScene的所有孩子

时间:2015-04-01 22:49:41

标签: ios swift

我正在尝试获取GameScene的所有子节点(由名称标识),以便与设备同步旋转某些SKSpriteNode。

目前我有这段代码:

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)
                }
            }
        }
    }
}  

我怎样才能得到孩子?是这样做的好方法吗?否则,我可以处理一个数组列表,我的所有孩子都添加到GameScene ...

1 个答案:

答案 0 :(得分:3)

在swift中,您可以使用以下方法枚举具有特定名称的所有子节点:

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

<强>文档: https://developer.apple.com/library/ios/documentation/SpriteKit/Reference/SKNode_Ref/index.html#//apple_ref/occ/instm/SKNode/enumerateChildNodesWithName:usingBlock