
雪のブロックでかまくらをつくるイメージでiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@import SceneKit;
@interface ViewController ()
@property (nonatomic, weak) SCNView *sceneView;
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
[self setupScene];
[self createGround];
[self createSnowDome];
[self createLight];
}
– (void)setupScene {
float w = CGRectGetMaxX(self.view.bounds);
SCNView *sv = [[SCNView alloc] initWithFrame:CGRectMake(0, 0, w, w)];
sv.backgroundColor = [self color:2];
sv.scene = [SCNScene scene];
[self.view addSubview:sv];
self.sceneView = sv;
}
– (void)createGround {
SCNBox *ground = [SCNBox boxWithWidth:40 height:1 length:40 chamferRadius:0];
ground.firstMaterial.diffuse.contents = [self color:3];
SCNNode *groundNode = [SCNNode nodeWithGeometry:ground];
groundNode.physicsBody = [SCNPhysicsBody staticBody];
[self.sceneView.scene.rootNode addChildNode:groundNode];
}
– (void)createSnowDome {
static int counter = (1 + 2 + 3 + 4 + 5) * 4;
static int floor = 5;
int nextFloorStart = 0;
for (int i=1; i<floor; i++) nextFloorStart += i * 4;
SCNBox *snowBlock = [SCNBox boxWithWidth:3 + floor * 0.2 height:3 length:4 chamferRadius:0];
int coloridx[] = {0, 1, 4};
snowBlock.firstMaterial.diffuse.contents = [self color:coloridx[arc4random_uniform(2)]];
SCNNode *snowblockNode = [SCNNode nodeWithGeometry:snowBlock];
snowblockNode.physicsBody = [SCNPhysicsBody dynamicBody];
snowblockNode.physicsBody.velocityFactor = SCNVector3Make(0, 1, 0);
snowblockNode.physicsBody.angularVelocityFactor = SCNVector3Make(0, 1, 0);
[self.sceneView.scene.rootNode addChildNode:snowblockNode];
float r = floor * 3;
float angle = (counter – nextFloorStart) * M_PI / (2.0 * floor);
float x = r * cos(angle);
float z = r * sin(angle);
snowblockNode.position = SCNVector3Make(x, 30, z);
snowblockNode.rotation = SCNVector4Make(0, 1, 0, M_PI/2.0 – angle);
counter–;
if (counter < nextFloorStart) floor–;
}
– (void)createLight {
SCNLight *light2 = [SCNLight light];
light2.type = SCNLightTypeOmni;
light2.color = [UIColor whiteColor];
SCNNode *lightNode2 = [SCNNode node];
lightNode2.light = light2;
lightNode2.position = SCNVector3Make(0, 40, 80);
lightNode2.rotation = SCNVector4Make(1, 0, 0, –0.4);
[self.sceneView.scene.rootNode addChildNode:lightNode2];
SCNLight *light = [SCNLight light];
light.type = SCNLightTypeAmbient;
light.color = [UIColor colorWithWhite:0.5 alpha:1];
SCNNode *lightNode = [SCNNode node];
lightNode.light = light;
[self.sceneView.scene.rootNode addChildNode:lightNode];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self createSnowDome];
}
#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 {
switch (i) {
case 0: return ColorHex(0xFFFFFF);
case 1: return ColorHex(0xF6FEFF);
case 2: return ColorHex(0xEA22FA);
case 3: return ColorHex(0xD6DDE5);
case 4: return ColorHex(0xC7C5C3);
}
return nil;
}
@end