2016-11-07 3 views
4

Я хотел бы знать, как я могу анимировать цвет SCNNode с помощью Swift.Как добавить анимацию для изменения цвета SceneKit в SNCNode?

Например: Я хотел бы, чтобы узел постоянно менял цвет, или я хотел бы, чтобы узел исчезал от черного до синего.

Я использую SCNAction fadeIn или fadeOut?

Заранее благодарен!

ответ

3

Got идея от @Luca Angeletti, я пишу код таким образом, мы можем анимировать между любыми цветами, включают их альфы:

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 
} 

Использование:

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) 
11

Вы можете создать собственное действие.

Если у вас есть красный шар в сцене

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

Это, как вы строите пользовательские действия

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 
} 

Наконец вам просто нужно выполнить действие на сфере

sphereNode.runAction(changeColor) 

enter image description here

Смежные вопросы