Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change color of SCNNode/Geometry/Material

I am very new to SceneKit, and am starting a test application. I have a little cube that moves around. I would like to add axes (X, Y, Z). I have created them like so.

    SCNVector3 xPositions[] = {SCNVector3Make(-50, 0, 0), SCNVector3Make(50, 0, 0)};

    int indicies[] = {0, 1};
    NSData *indexData = [NSData dataWithBytes:indicies length:sizeof(indicies)];

// X axis
    SCNGeometrySource *xSource = [SCNGeometrySource geometrySourceWithVertices:xPositions count:2];
    SCNGeometryElement *xElement = [SCNGeometryElement geometryElementWithData:indexData primitiveType:SCNGeometryPrimitiveTypeLine primitiveCount:2 bytesPerIndex:sizeof(int)];
    SCNGeometry *xAxis = [SCNGeometry geometryWithSources:@[xSource] elements:@[xElement]];
    SCNNode *xNode = [SCNNode nodeWithGeometry:xAxis];
    [self.gameView.scene.rootNode addChildNode:xNode];

    // Y axis
    SCNVector3 yPositions[] = {SCNVector3Make(0, -50, 0), SCNVector3Make(0, 50, 0)};
    SCNGeometrySource *ySource = [SCNGeometrySource geometrySourceWithVertices:yPositions count:2];
    SCNGeometryElement *yElement = [SCNGeometryElement geometryElementWithData:indexData primitiveType:SCNGeometryPrimitiveTypeLine primitiveCount:2 bytesPerIndex:sizeof(int)];
    SCNGeometry *yAxis = [SCNGeometry geometryWithSources:@[ySource] elements:@[yElement]];
    SCNNode *yNode = [SCNNode nodeWithGeometry:yAxis];
    [self.gameView.scene.rootNode addChildNode:yNode];

    // Z axis
    SCNVector3 zPositions[] = {SCNVector3Make(0, 0, -50), SCNVector3Make(0, 0, 50)};
    SCNGeometrySource *zSource = [SCNGeometrySource geometrySourceWithVertices:zPositions count:2];
    SCNGeometryElement *zElement = [SCNGeometryElement geometryElementWithData:indexData primitiveType:SCNGeometryPrimitiveTypeLine primitiveCount:2 bytesPerIndex:sizeof(int)];
    SCNGeometry *zAxis = [SCNGeometry geometryWithSources:@[zSource] elements:@[zElement]];
    SCNNode *zNode = [SCNNode nodeWithGeometry:zAxis];
    [self.gameView.scene.rootNode addChildNode:zNode];

My problem is that I would like to change the color on them so I can tell which is which. Is there a way I can do that, or do I have to create my lines another way? I'm making a mac app, not an iOS app, just an fyi. Also, I know about repeating code, I was just tired and i will fix that.

like image 526
Minebomber Avatar asked Nov 20 '15 14:11

Minebomber


1 Answers

Change the geometry's material, using either -firstMaterial or (if it's a complicated object) the -materials array.

SCNMaterial *redMaterial = [SCNMaterial new];
redMaterial.diffuse.contents = [NSColor redColor];
xAxis.firstMaterial = redMaterial;

Or more concisely:

yAxis.firstMaterial.diffuse.contents = [NSColor magentaColor];
zAxis.firstMaterial.diffuse.contents = [NSColor yellowColor];
like image 84
Hal Mueller Avatar answered Oct 26 '22 09:10

Hal Mueller