How to create geometry in SceneKit

Small code example, how to create 3D Geometry in SceneKit from scratch. Apple didnt provide any samples, so i hope this will be useful for someone.

SCNNode *myNode = [SCNNode nodeWithGeometry:[self createGeometry]];

- (SCNGeometry *) createGeometry{

NSArray *sources = @[
[SCNGeometrySource geometrySourceWithVertices: (SCNVector3[]){
{.x = -1.0f, .y = -1.0f, .z = 0.0f},
{.x = -1.0f, .y = 1.0f, .z = 0.0f},
{.x = 1.0f, .y = 1.0f, .z = 0.0f},
{.x = 1.0f, .y = -1.0f, .z = 0.0f}
} count:4],
[SCNGeometrySource geometrySourceWithNormals:(SCNVector3[]){
{.x = 0.0f, .y = 0.0f, .z = -1.0f},
{.x = 0.0f, .y = 0.0f, .z = -1.0f},
{.x = 0.0f, .y = 0.0f, .z = -1.0f},
{.x = 0.0f, .y = 0.0f, .z = -1.0f}
} count:4],
[SCNGeometrySource geometrySourceWithTextureCoordinates:(CGPoint[]){
{.x = 0.0f, .y = 0.0f},
{.x = 0.0f, .y = 1.0f},
{.x = 1.0f, .y = 1.0f},
{.x = 1.0f, .y = 0.0f}
} count:4]
];

NSArray *elements = @[
[SCNGeometryElement geometryElementWithData:[NSData dataWithBytes:(short[]){0, 2, 3,0,1,2} length:sizeof(short[6])]
primitiveType:SCNGeometryPrimitiveTypeTriangles
primitiveCount:2
bytesPerIndex:sizeof(short)]];

SCNGeometry *geo = [SCNGeometry geometryWithSources:sources elements:elements];

SCNMaterial *mat = [SCNMaterial material];
mat.diffuse.contents = [NSColor redColor];

geo.firstMaterial = mat;
geo.firstMaterial.doubleSided = YES;

return geo;

}

 

Leave a Comments [ Trackback | RSS 2.0 ]

Have Your Say »

(will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>