Fredrik
Fredrik

Reputation: 3293

Scenekit: Add animation to SCNNode from external Collada

I initialize my Scene like this

// Load COLLADA Character
let myScene = SCNScene(named: "Characters.scnassets/Police/Police.dae")

// Recurse through all the child nodes in the Character and add to characterNode
for node in myScene!.rootNode.childNodes as [SCNNode]
{
    characterNode.addChildNode(node)
}

// Add characterNode to scene
self.rootNode.addChildNode(characterNode)

Is it possible to add an animation to characterNode from an external DAE? It is autorigged through Mixamo.

Upvotes: 1

Views: 1505

Answers (1)

James P
James P

Reputation: 4836

Apple has an example in their Fox Scenekit app.

The following function loads an animation from your art.scnassets folder:

- (CAAnimation *)animationFromSceneNamed:(NSString *)path {
    SCNScene *scene = [SCNScene sceneNamed:path];
    __block CAAnimation *animation = nil;

    [scene.rootNode enumerateChildNodesUsingBlock:^(SCNNode *child, BOOL *stop) {
        if (child.animationKeys.count > 0) {
            animation = [child animationForKey:child.animationKeys[0]];
            *stop = YES;
        }
    }];

    return animation;
}

Which you can then add to your characterNode:

CAAnimation *animation = [self animationFromSceneNamed:@"art.scnassets/characterAnim.scn"];
[characterNode addAnimation:animation forKey:@"characterAnim"];

This should be the equivalent function in Swift, but I haven't had a chance to test it.

func animationFromSceneNamed(path: String) -> CAAnimation? {
    let scene  = SCNScene(named: path)
    var animation:CAAnimation?
    scene?.rootNode.enumerateChildNodes({ child, stop in
        if let animKey = child.animationKeys.first {
            animation = child.animation(forKey: animKey)
            stop.pointee = true
        }
    })
    return animation
}

Upvotes: 2

Related Questions