17.Jan.2013 at 17 | Den Ivanov
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;
}
Your example is helpful for me. Thanks a lot!