
輪っかをくるっと半回転させるiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@import SceneKit;
@interface ViewController ()
@property (nonatomic, weak) SCNView *sceneView;
@property (nonatomic) int count;
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
[self setupScene];
[self createGround];
[self createHoops];
[self createCamera];
[self createLight];
}
– (void)setupScene {
SCNView *sv = [[SCNView alloc] initWithFrame:self.view.bounds];
sv.backgroundColor = [self color:0];
sv.scene = [SCNScene scene];
sv.allowsCameraControl = YES;
[self.view addSubview:sv];
self.sceneView = sv;
}
– (void)createGround {
SCNBox *ground = [SCNBox boxWithWidth:50 height:2 length:50 chamferRadius:0];
ground.firstMaterial.diffuse.contents = [self color:1];
SCNNode *groundNode = [SCNNode nodeWithGeometry:ground];
groundNode.physicsBody = [SCNPhysicsBody staticBody];
[self.sceneView.scene.rootNode addChildNode:groundNode];
}
– (void)createHoops {
for (int i=0; i<10; i++) {
SCNTorus *t = [SCNTorus torusWithRingRadius:5 pipeRadius:0.3];
int type = (i % 3) + 2;
t.firstMaterial.diffuse.contents = [self color:type];
SCNNode *hoop = [SCNNode nodeWithGeometry:t];
hoop.name = [NSString stringWithFormat:@”hoop%d”, 9 – i];
hoop.position = SCNVector3Make(-15, 3 + i, 0);
hoop.physicsBody = [SCNPhysicsBody dynamicBody];
[self.sceneView.scene.rootNode addChildNode:hoop];
}
}
– (void)createCamera {
SCNNode *camera = [SCNNode node];
camera.camera = [SCNCamera camera];
camera.camera.zFar = 150;
camera.position = SCNVector3Make(0, 40, 80);
camera.rotation = SCNVector4Make(1, 0, 0, –0.2);
[self.sceneView.scene.rootNode addChildNode:camera];
}
– (void)createLight {
SCNLight *l = [SCNLight light];
l.type = SCNLightTypeOmni;
SCNNode *light = [SCNNode node];
light.light = l;
light.position = SCNVector3Make(0, 20, 60);
[self.sceneView.scene.rootNode addChildNode:light];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSString *name = [NSString stringWithFormat:@”hoop%d”, self.count++];
SCNNode *hoop = [self.sceneView.scene.rootNode childNodeWithName:name recursively:NO];
[hoop.physicsBody applyForce:SCNVector3Make(10, 20, 0) atPosition:SCNVector3Make(-0.4, 0, 0) impulse:YES];
}
#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 val[] = {0xAF7575, 0xEFD8A1, 0xBCD693, 0xAFD7DB, 0x3D9CA8};
return ColorHex(val[i]);
}
@end