更改子节点的颜色

Shm*_*idt 2 scenekit swift ios8

目前,当我改变孩子的节点颜色时,它将导致所有其他子节点的颜色变化,这是我不想要的.

我这样改变子节点的颜色:

let materials = node.geometry?.materials as! [SCNMaterial]
let material = materials[0]
material.diffuse.contents = UIColor.grayColor()
Run Code Online (Sandbox Code Playgroud)

ric*_*ter 10

默认情况下,如果您有多个节点SCNGeometry分配了相同的实例,那么这些节点也具有相同的材料.更改材质会更改使用该材质的所有节点的外观.

一个SCNGeometry对象并不直接代表几何数据-它实际上是一组几何数据和一组材料之间的关联只是一个轻量级表示.因此,当您想要在具有不同材质的多个节点上渲染相同的几何体时,只需复制几何对象......它们仍将共享基础数据,因此渲染时间成本可忽略不计,但您将能够更改他们的材料独立.

复制几何图形后,可以单独更改两个几何图形上的材料,但这些集仍然共享相同的SCNMaterial实例.(这很有用,因为几何体可以包含多种材质,每种材质都是一组属性,因此尽可能有效地共享它们.)因此,您可以为每个几何体分配新材质,也可以取消共享材质.

// Using copy as a way to get two nodes with the same material
// (but your scene might already have two such nodes)
let node2 = node1.copy() as! SCNNode 

// Right now, node2 is sharing geometry. This changes the color of both:
node1.geometry?.firstMaterial?.diffuse.contents = UIColor.redColor()

// Un-share the geometry by copying
node2.geometry = node1.geometry!.copy()
// Un-share the material, too
node2.geometry?.firstMaterial = node1.geometry!.firstMaterial!.copy() as? SCNMaterial
// Now, we can change node2's material without changing node1's:
node2.geometry?.firstMaterial?.diffuse.contents = UIColor.blueColor()
Run Code Online (Sandbox Code Playgroud)

在WWDC 2014关于使用SceneKit构建游戏的演讲中有一个很好的讨论.相关位在视频中约为37:15,在PDF中为幻灯片159.


Shm*_*idt 6

基于@sambro评论和@rickster代码,这是现成的答案:

// Un-share the geometry by copying
node.geometry = node.geometry!.copy() as? SCNGeometry
// Un-share the material, too
node.geometry?.firstMaterial = node.geometry?.firstMaterial!.copy() as? SCNMaterial
// Now, we can change node's material without changing parent and other childs:
node.geometry?.firstMaterial?.diffuse.contents = UIColor.blueColor()
Run Code Online (Sandbox Code Playgroud)