SceneKit从单独的scn文件加载带有动画的节点

我有一个动态创建SCNView的视图。 它的场景是空的,但是当我按下一个按钮时,我想从单独的scn文件中添加一个节点。 这个文件包含动画,我想在主场景中设置动画。 问题是在将对象添加到场景后,它不是动画。 当我将此文件用作SCNView场景时,它可以工作。 isPlaying和循环已启用。 使用动画导入这样的节点还需要做什么? 示例代码如下:

override func viewDidLoad() { super.viewDidLoad() let scene = SCNScene() let sceneView = SCNView(frame: CGRect(x: 0, y: 0, width: 300, height: 300)) sceneView.scene = scene sceneView.loops = true sceneView.isPlaying = true sceneView.autoenablesDefaultLighting = true view.addSubview(sceneView) let subNodeScene = SCNScene(named: "Serah_Animated.scn")! let serah = subNodeScene.rootNode.childNode(withName: "main", recursively: false)! scene.rootNode.addChildNode(serah) } 

您只需要检索动画:

  [childNode enumerateChildNodesUsingBlock:^(SCNNode *child, BOOL *stop) { for(NSString *key in child.animationKeys) { // for every animation key CAAnimation *animation = [child animationForKey:key]; // get the animation animation.usesSceneTimeBase = NO; // make it system time based animation.repeatCount = FLT_MAX; // make it repeat forever [child addAnimation:animation forKey:key]; // animations are copied upon addition, so we have to replace the previous animation } }]; 

您需要从场景Serah_Animated.scn获取动画,它将是一个CAAnimation对象。 然后,将该动画对象添加到主场景的rootNode中。

 let animScene = SCNSceneSource(url:<>) let animation:CAAnimation = animScene.entryWithIdentifier(<>, withClass:CAAnimation.self) 

您可以使用Xcode中的场景编辑器从.scn文件中找到animID,如下所示。

来自Xcode场景编辑器的SceneKit AnimationID

现在,您可以将动画对象添加到根节点。

 scene.rootNode.addAnimation(animation, forKey:<>) 

请注意,我们正在重用animID,这样您还可以从节点中删除动画。

 scene.rootNode.removeAnimation(forKey:<>) 
  • 我的解决方案假设您的动画是单个动画。 如果您看到一堆动画,则需要添加所有动画节点。 在我的工作流程中,我在Blender中有文件导出为Collada格式,然后使用Automated Collada Converter确保我有单个动画节点。
  • 相关的答案
  • 您还可以使用entriesWithIdentifiersOfClass(CAAnimation.self) animID编程方式获取animID ,当您拥有一堆动画而不是上面的单个动画时,或者如果您只想添加动画而不animID先处理animID ,则animID
  • 用于场景工具包动画的Apple示例代码 ,请注意示例代码在ObjC中,但转换到Swift应该是直截了当的。