2016-12-13 66 views
4

我有一個動態創建SCNView的視圖。它的場景是空的,但是當我按下一個按鈕時,我想從單獨的scn文件中添加一個節點。這個文件包含動畫,我希望它在主場景中動畫。問題在於,在向場景添加對象之後,它不具有動畫效果。當我將這個文件作爲SCNView場景使用時。 isPlaying和循環已啓用。我還需要做什麼才能導入帶有動畫的節點?下面的示例代碼:SceneKit從獨立scn文件加載節點的動畫

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) 


} 
+0

與你同樣的問題,你解決了嗎? – ooOlly

回答

3

您需要從場景Serah_Animated.scn,這將是一個CAAnimation對象獲取動畫。然後,將該動畫對象添加到主場景的根節點。

let animScene = SCNSceneSource(url:<<URL to your scene file", options:<<Scene Loading Options>>) 
let animation:CAAnimation = animScene.entryWithIdentifier(<<animID>>, withClass:CAAnimation.self) 

您可以從.scn文件中使用Xcode中的場景編輯器,找到animID,如下圖所示。

SceneKit AnimationID from the Xcode Scene Editor

現在可以將動畫對象添加到您的根節點。

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

請注意,我們正在重新使用animID,這將允許您從節點中刪除動畫。上述

scene.rootNode.removeAnimation(forKey:<<animId>>) 
  • 我的解決方案假定您的動畫是一個動畫。如果看到一堆動畫,則需要添加所有動畫節點。在我的工作流程中,我將Blender中的文件導出爲Collada格式,然後使用Automated Collada Converter確保我有單個動畫節點。
  • Related SO answer
  • 您也可以獲取animID編程方式使用entriesWithIdentifiersOfClass(CAAnimation.self),有用的,當你有一大堆的動畫,而不是一個單一的動畫如上或者如果你只是想添加動畫,而不理會的animID前手。
  • Apple Sample Code for scene kit animations,請注意示例代碼位於ObjC中,但翻譯爲Swift應該是直截了當的。
+2

我在.scn文件中沒有找到實體列表。它只存在於.dae文件 – ooOlly

4

所有你需要的是檢索動畫:

 [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 
     } 
    }]; 
+0

謝謝@ooOlly。 –