
ボールを当てると回転する壁を表示する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 createWall];
[self createCamera];
}
– (void)setupScene {
SCNView *sv = [[SCNView alloc] initWithFrame:self.view.bounds];
sv.backgroundColor = [UIColor lightGrayColor];
sv.scene = [SCNScene scene];
sv.autoenablesDefaultLighting = YES;
[self.view addSubview:sv];
self.sceneView = sv;
}
– (void)createGround {
SCNBox *ground = [SCNBox boxWithWidth:20 height:0.2 length:40 chamferRadius:1];
ground.firstMaterial.diffuse.contents = [UIColor greenColor];
SCNNode *groundNode = [SCNNode nodeWithGeometry:ground];
groundNode.physicsBody = [SCNPhysicsBody staticBody];
[self.sceneView.scene.rootNode addChildNode:groundNode];
}
– (void)createWall {
SCNBox *wall = [SCNBox boxWithWidth:4 height:6 length:0.2 chamferRadius:0];
wall.firstMaterial.diffuse.contents = [UIColor brownColor];
for (int i=0; i<5; i++) {
SCNNode *wallNode = [SCNNode nodeWithGeometry:wall];
wallNode.position = SCNVector3Make(i * 4 – 8, 3.15, 0);
wallNode.physicsBody = [SCNPhysicsBody dynamicBody];
wallNode.physicsBody.velocityFactor = SCNVector3Make(0, 0, 0);
wallNode.physicsBody.angularVelocityFactor = SCNVector3Make(0, 1, 0);
[self.sceneView.scene.rootNode addChildNode:wallNode];
}
}
– (void)createCamera {
SCNNode *camera = [SCNNode node];
camera.camera = [SCNCamera camera];
camera.position = SCNVector3Make(0, 10, 50);
camera.rotation = SCNVector4Make(1, 0, 0, –0.1);
[self.sceneView.scene.rootNode addChildNode:camera];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint p = [touches.anyObject locationInView:self.view];
SCNSphere *ball = [SCNSphere sphereWithRadius:0.5];
ball.firstMaterial.diffuse.contents = [UIColor yellowColor];
SCNNode *ballNode = [SCNNode nodeWithGeometry:ball];
ballNode.position = SCNVector3Make(20.0 * p.x / CGRectGetMaxX(self.view.bounds) – 10.0, 2, 20);
[self.sceneView.scene.rootNode addChildNode:ballNode];
ballNode.physicsBody = [SCNPhysicsBody dynamicBody];
[ballNode.physicsBody applyForce:SCNVector3Make(0, 0.5, –20) impulse:YES];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[ballNode removeFromParentNode];
});
}
@end