
花がぽつぽつ咲いていくiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@import SceneKit;
@interface ViewController ()
@property (nonatomic, weak) SCNView *sceneView;
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
[self setupScene];
[self createGreenField];
[self createFlower];
}
– (void)setupScene {
SCNView *sv = [[SCNView alloc] initWithFrame:self.view.bounds];
sv.backgroundColor = [self color:2];
sv.scene = [SCNScene scene];
sv.allowsCameraControl = YES;
[self.view addSubview:sv];
self.sceneView = sv;
}
– (void)createGreenField {
SCNCylinder *field = [SCNCylinder cylinderWithRadius:5 height:0.2];
field.firstMaterial.diffuse.contents = [self color:0];
SCNNode *fieldNode = [SCNNode nodeWithGeometry:field];
[self.sceneView.scene.rootNode addChildNode:fieldNode];
for (int i=0; i<100; i++) {
float x = (i%10) – 4.5;
float z = (i/10) – 4.5;
for (int j=0; j<6; j++) {
if (sqrt(pow(x, 2) + pow(z, 2)) > 5) {
continue;
}
SCNBox *green = [SCNBox boxWithWidth:0.05 height:0.3 length:0.05 chamferRadius:0];
green.firstMaterial.diffuse.contents = [self color:1];
SCNNode *greenNode = [SCNNode nodeWithGeometry:green];
greenNode.pivot = SCNMatrix4MakeTranslation(0, –0.15, 0);
greenNode.position = SCNVector3Make(x, 0, z);
[self.sceneView.scene.rootNode addChildNode:greenNode];
greenNode.rotation = SCNVector4Make(0, 1, 0, j * M_PI / 3.0);
[greenNode runAction:[SCNAction rotateByX:0.4 y:0 z:0 duration:0.5]];
}
}
}
– (void)createFlower {
for (int i=0; i<30; i++) {
float r = 3.5 * arc4random_uniform(10) * 0.1 + 1;
float w = M_PI * arc4random_uniform(20) * 0.1;
SCNNode *flower = [SCNNode node];
flower.position = SCNVector3Make(r * cos(w), 0, r * sin(w));
flower.name = @”flower”;
[self.sceneView.scene.rootNode addChildNode:flower];
for (int j=0; j<6; j++) {
SCNBox *f = [SCNBox boxWithWidth:0.2 height:0.5 length:0.1 chamferRadius:0.1];
f.firstMaterial.diffuse.contents = [self color:(j%2) + 3];
SCNNode *fNode = [SCNNode nodeWithGeometry:f];
fNode.pivot = SCNMatrix4MakeTranslation(0, –0.25, 0);
fNode.rotation = SCNVector4Make(0, 1, 0, j * M_PI / 3.0);
[flower addChildNode:fNode];
}
}
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
static int i = 0;
for (SCNNode *n in self.sceneView.scene.rootNode.childNodes) {
if ([n.name isEqual:@”flower”]) {
++i;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * i * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[[n childNodes] enumerateObjectsUsingBlock:^(SCNNode *child, NSUInteger idx, BOOL *stop) {
[child runAction:[SCNAction rotateByX:0.8 y:0 z:0 duration:0.5]];
}];
});
}
}
}
#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 > 4) {
return nil;
}
int colorCode[] = {0x289976, 0x67CC8E, 0xB1FF91, 0xFFE877, 0xFF5600};
return ColorHex(colorCode[i]);
}
@end