ボールの軌跡でタワーを作るiPhoneアプリのサンプルコードを描いてみます。
#import “ViewController.h”
@import SceneKit;
@interface ViewController () <SCNSceneRendererDelegate>
@property (nonatomic, weak) SCNView *sceneView;
@end
@implementation ViewController
– (void)viewDidLoad {
[super viewDidLoad];
[self setupScene];
[self createReflector];
[self createBall];
[self createCamera];
}
– (void)setupScene {
SCNView *sv = [[SCNView alloc] initWithFrame:self.view.bounds];
sv.delegate = self;
sv.backgroundColor = [UIColor blackColor];
sv.scene = [SCNScene scene];
sv.allowsCameraControl = YES;
sv.scene.paused = YES;
sv.scene.physicsWorld.gravity = SCNVector3Zero;
[self.view addSubview:sv];
self.sceneView = sv;
}
– (void)createReflector {
SCNMatrix4 t1 = SCNMatrix4Identity;
t1 = SCNMatrix4Rotate(t1, M_PI * 0.41, 0, 0, 1);
t1 = SCNMatrix4Translate(t1, 20, 0, 0);
SCNMatrix4 t2 = SCNMatrix4Identity;
t2 = SCNMatrix4Rotate(t2, M_PI/2.0, 0, 0, 1);
t2 = SCNMatrix4Translate(t2, –12, 18, 0);
SCNMatrix4 t3 = SCNMatrix4Identity;
t3 = SCNMatrix4Rotate(t3, M_PI/2.6, 0, 0, 1);
t3 = SCNMatrix4Translate(t3, 8, 30, 0);
SCNMatrix4 t4 = SCNMatrix4Identity;
t4 = SCNMatrix4Translate(t4, 0, 50, 0);
SCNMatrix4 transforms[] = {t1, t2, t3, t4};
for (int i=0; i<4; i++) {
SCNCylinder *cylinder = [SCNCylinder cylinderWithRadius:3 height:1];
cylinder.firstMaterial.diffuse.contents = [UIColor lightGrayColor];
SCNNode *reflector = [SCNNode nodeWithGeometry:cylinder];
reflector.transform = transforms[i];
[self.sceneView.scene.rootNode addChildNode:reflector];
reflector.physicsBody = [SCNPhysicsBody staticBody];
reflector.physicsBody.restitution = 1.0;
}
}
– (void)createBall {
SCNSphere *sphere = [SCNSphere sphereWithRadius:1];
sphere.firstMaterial.diffuse.contents = [[UIColor yellowColor] colorWithAlphaComponent:0.8];
SCNNode *ball = [SCNNode nodeWithGeometry:sphere];
ball.name = @”ball”;
ball.physicsBody = [SCNPhysicsBody dynamicBody];
ball.physicsBody.restitution = 1.0;
ball.physicsBody.damping = 0;
ball.physicsBody.friction = 0;
[self.sceneView.scene.rootNode addChildNode:ball];
ball.position = SCNVector3Make(-20, 0, 0);
}
– (void)createCamera {
SCNNode *camera = [SCNNode node];
camera.camera = [SCNCamera camera];
camera.camera.zFar = 300;
camera.position = SCNVector3Make(0, 30, 120);
[self.sceneView.scene.rootNode addChildNode:camera];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
SCNNode *ball = [self.sceneView.scene.rootNode childNodeWithName:@”ball” recursively:NO];
self.sceneView.scene.paused = NO;
[ball.physicsBody applyForce:SCNVector3Make(30, 0, 0) impulse:YES];
}
– (void)renderer:(id<SCNSceneRenderer>)aRenderer didRenderScene:(SCNScene *)scene atTime:(NSTimeInterval)time
{
if (scene.paused) {
return;
}
SCNNode *ball = [scene.rootNode childNodeWithName:@”ball” recursively:NO];
SCNNode *afterimage = [SCNNode nodeWithGeometry:ball.geometry];
afterimage.position = ball.presentationNode.position;
[scene.rootNode addChildNode:afterimage];
}
@end