Matthew Anguelo Matthew Anguelo - 28 days ago 25
Swift Question

How to Add Animations to Change SNCNode's Color SceneKit?

I would like to know how I can animate an SCNNode's color using Swift.

For example: I would like the node to constantly be changing color or I would like the node to fade from black to blue.

do I use the SCNAction fadeIn or fadeOut?

Thanks in advance!

Answer

You can create a custom action.

If you have a red sphere in your scene

let sphereNode = scene.rootNode.childNode(withName: "sphere", recursively: false)!
sphereNode.geometry!.firstMaterial!.diffuse.contents = UIColor.red

This is how you build the custom action

let changeColor = SCNAction.customAction(duration: 10) { (node, elapsedTime) -> () in
    let percentage = elapsedTime / 5
    let color = UIColor(red: 1 - percentage, green: percentage, blue: 0, alpha: 1)
    node.geometry!.firstMaterial!.diffuse.contents = color
}

Finally you just need to run the action on the sphere

sphereNode.runAction(changeColor)

Result

enter image description here

Comments