0

I've successfully built and displayed a custom geometry (a cube) in SceneKit from this post

Custom Geometry

Now, I want to set the color of each face to a different color. I found this post that supposed to do that

Per Vertex Color

Unfortunately, I can't seem to set the color of a face of the cube to a specific color. For example, if I set the color of all vertices to SCNVector3(x:1,y:0,z:0), I would expect all faces to be red, but, instead, they're all green. Setting the colors to SCNVector3(x:0,y:1,z:0) turns the faces black. Here's the relevant code

let colors = [SCNVector3](count:vertices.count, repeatedValue:SCNVector3(x:1, y:0, z:0))

let colorData = NSData(bytes: colors, length: sizeof(SCNVector3) * colors.count)
let colorSource = SCNGeometrySource(data: colorData, semantic: SCNGeometrySourceSemanticColor, vectorCount: colors.count, floatComponents: true, componentsPerVector: 3, bytesPerComponent: sizeof(Float), dataOffset: 0, dataStride: sizeof(SCNVector3))

let geometry = SCNGeometry(sources: [colorSource, vertexSource, normalSource], elements: [element])

// Create a node and assign our custom geometry
let node = SCNNode()

let material = SCNMaterial()
material.diffuse.contents = NSColor.whiteColor()
geometry.materials = [material]

node.geometry = geometry

Does anyone know why it's not working?

Epsilon
  • 1,016
  • 1
  • 6
  • 15

1 Answers1

0

You have to create a material per face with a different color.

For example:

let material1 = SCNMaterial()
material1.diffuse.contents = NSColor.whiteColor()
let material2 = SCNMaterial()
material2.diffuse.contents = NSColor.greenColor()
let material3 = SCNMaterial()
material3.diffuse.contents = NSColor.redColor()
let material4 = SCNMaterial()
material4.diffuse.contents = NSColor.blackColor()
let material5 = SCNMaterial()
material5.diffuse.contents = NSColor.blueColor()
let material6 = SCNMaterial()
material6.diffuse.contents = NSColor.whiteColor()

geometry.materials = [material1,material2,material3,material4,material5,material6]
Stefan
  • 5,203
  • 8
  • 27
  • 51
  • This will work for geometries with relatively few faces, such as a cube. I would like to build something much more complex with thousands of vertices and need to set the color of each vertex. – Epsilon Dec 21 '18 at 08:00