
カメラを回すと、六角形が立方体に早変わりなiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@import SceneKit;
@interface ViewController ()
@property (nonatomic, weak) SCNView *sceneView;
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
[self setupScene];
[self createBox];
[self createCamera];
}
– (void)setupScene {
SCNView *sv = [[SCNView alloc] initWithFrame:self.view.bounds];
sv.scene = [SCNScene scene];
sv.allowsCameraControl = YES;
sv.backgroundColor = [self color:1];
[self.view addSubview:sv];
self.sceneView = sv;
}
– (void)createBox {
float l = 1;
for (int j=0; j< pow(3, 3); j++) {
float x = (j % 3) * l – l;
float y = (j / 3 % 3) * l – l;
float z = (j / 9) * l – l;
SCNNode *box = [SCNNode node];
box.position = SCNVector3Make(x, y, z);
[self.sceneView.scene.rootNode addChildNode:box];
for (int i=0; i<12; i++) {
SCNBox *wire = [SCNBox boxWithWidth:l height:0.05 length:0.05 chamferRadius:0];
wire.firstMaterial.diffuse.contents = [self color:0];
SCNNode *wireNode = [SCNNode nodeWithGeometry:wire];
wireNode.transform = SCNMatrix4Translate(wireNode.transform, 0, 0.7 * l, 0);
wireNode.transform = SCNMatrix4Rotate(wireNode.transform, M_PI * 0.5 * i + M_PI * 0.25, 1, 0, 0);
if (i<4)
wireNode.transform = SCNMatrix4Rotate(wireNode.transform, M_PI * 0.5, 0, 1, 0);
else if (i<8)
wireNode.transform = SCNMatrix4Rotate(wireNode.transform, M_PI * 0.5, 0, 0, 1);
[box addChildNode:wireNode];
}
}
}
– (void)createCamera {
SCNNode *camera = [SCNNode node];
camera.camera = [SCNCamera camera];
camera.camera.zNear = –100;
camera.camera.usesOrthographicProjection = YES;
camera.camera.orthographicScale = 2;
[self.sceneView.scene.rootNode addChildNode:camera];
}
#define ColorHex(rgb) [UIColor colorWithRed:((rgb & 0xFF0000)>>16)/255.0 green:((rgb & 0xFF00)>>8)/255.0 blue:(rgb & 0xFF)/255.0 alpha:1.0]
– (UIColor *)color:(int)i {
if (i > 2) return nil;
int colorCode[] = {0xFFFFFF, 0x000000};
return ColorHex(colorCode[i]);
}
@end