'Creating a polygon made-up of multiple polygons in SceneKit with swift

Swift 5.5 iOS 15

Trying to build something like this--that comes from the Apple docx pages.

polygon

But cannot seem to work out how the indexes value works.

 var vertex:[SCNVector3] = []

    vertex.append(SCNVector3(x:0, y:0, z:0)) // 0
    vertex.append(SCNVector3(x:1, y:0, z:0)) // 1
    vertex.append(SCNVector3(x:1, y:1, z:0)) // 2
    vertex.append(SCNVector3(x:0, y:1, z:0)) // 3
    
    
   let indices:[Int32] = [4] + [0,1,2,3]

   return self.createGeometry(
        vertices:vertex, indices: indices,
        primitiveType: SCNGeometryPrimitiveType.polygon)

// extension

 internal func createGeometry5(vertices:[SCNVector3], indices:[Int32], primitiveType:SCNGeometryPrimitiveType) -> SCNGeometry {
    let verticesX = SCNGeometrySource(vertices: vertices)
    let indexData = Data(bytes: indices,
                                 count: indices.count * MemoryLayout<Int32>.size)
    let element = SCNGeometryElement(data: indexData,
                                             primitiveType: .polygon,
                                             primitiveCount: 1,
                                             bytesPerIndex: MemoryLayout<Int32>.size)
    return SCNGeometry(sources: [verticesX], elements: [element])
}

This works and produces a square-- but how to add a second square to the mix? I try this for example...

  vertex.append(SCNVector3(x:-1, y:0, z:0)) // 4
  vertex.append(SCNVector3(x:-1, y:1, z:0)) // 5

And change the indices

   let indices:[Int32] = [4, 4] + [0,1,2,3] + [0,1,4,5]

But it changes the first square to a triangle. I simply want to create a single geometric shape made up of multiple polygons. Multiple squares in fact.

So I change the last two vertex to this..

    vertex.append(SCNVector3(x:0, y:1, z:0)) // 4
    vertex.append(SCNVector3(x:-1, y:1, z:0)) // 5
    vertex.append(SCNVector3(x:-1, y:0, z:0)) // 6
    vertex.append(SCNVector3(x:0, y:0, z:0)) // 7

And the index to this

let indices:[Int32] = [4, 4] + [0,1,2,3] + [4,5,6,7]

And I get a single small square again??

enter image description here polygon



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source