如何添加动画来改变SNCNode的Color SceneKit?

Mat*_*elo 6 scenekit swift

我想知道如何使用Swift为SCNNode的颜色设置动画.

例如:我希望节点不断改变颜色,或者我希望节点从黑色渐变为蓝色.

使用SCNAction fadeIn或fadeOut?

提前致谢!

Luc*_*tti 18

您可以创建自定义操作.

如果场景中有红色球体

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

这是您构建自定义操作的方式

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
}
Run Code Online (Sandbox Code Playgroud)

最后,您只需要在球体上运行动作

sphereNode.runAction(changeColor)
Run Code Online (Sandbox Code Playgroud)

结果

在此输入图像描述


Ton*_*ony 9

@Luca Angeletti得到了想法,我编写代码,以便我们可以在任何颜色之间设置动画,包括它们的alphas:

func aniColor(from: UIColor, to: UIColor, percentage: CGFloat) -> UIColor {
    let fromComponents = from.cgColor.components!
    let toComponents = to.cgColor.components!

    let color = UIColor(red: fromComponents[0] + (toComponents[0] - fromComponents[0]) * percentage,
        green: fromComponents[1] + (toComponents[1] - fromComponents[1]) * percentage,
        blue: fromComponents[2] + (toComponents[2] - fromComponents[2]) * percentage,
        alpha: fromComponents[3] + (toComponents[3] - fromComponents[3]) * percentage)
    return color
}
Run Code Online (Sandbox Code Playgroud)

使用:

let oldColor = UIColor.red
let newColor = UIColor(colorLiteralRed: 0.0, green: 0.0, blue: 1.0, alpha: 0.5)
let duration: TimeInterval = 1
let act0 = SCNAction.customAction(duration: duration, action: { (node, elapsedTime) in
    let percentage = elapsedTime / CGFloat(duration)
    node.geometry?.firstMaterial?.diffuse.contents = self.aniColor(from: newColor, to: oldColor, percentage: percentage)
})
let act1 = SCNAction.customAction(duration: duration, action: { (node, elapsedTime) in
    let percentage = elapsedTime / CGFloat(duration)
    node.geometry?.firstMaterial?.diffuse.contents = self.aniColor(from: oldColor, to: newColor, percentage: percentage)
})

let act = SCNAction.repeatForever(SCNAction.sequence([act0, act1]))
node.runAction(act)
Run Code Online (Sandbox Code Playgroud)