iPhone顔ブロック

ブロックを押して顔を作るiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@import SceneKit;

@interface ViewController ()

@property (nonatomic, weak) SCNView *sceneView;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    [self setupScene];

    [self createWall];

    [self createLight];

    [self createCamera];

}

– (void)setupScene {

    SCNView *sv = [[SCNView alloc] initWithFrame:self.view.bounds];

    sv.backgroundColor = [UIColor lightGrayColor];

    sv.scene = [SCNScene scene];

    [self.view addSubview:sv];

    self.sceneView = sv;

}

– (void)createWall {

    SCNCylinder *base = [SCNCylinder cylinderWithRadius:5 height:0.1];

    base.firstMaterial.diffuse.contents = [UIColor brownColor];

    SCNNode *baseNode = [SCNNode nodeWithGeometry:base];

    baseNode.physicsBody = [SCNPhysicsBody staticBody];

    [self.sceneView.scene.rootNode addChildNode:baseNode];

    

    for (int i=0; i<64; i++) {

        float x = (i % 8) – 3.5;

        float y = 10;

        SCNBox *box = [SCNBox boxWithWidth:1 height:1 length:6 chamferRadius:0.01];

        box.firstMaterial.diffuse.contents = [UIColor greenColor];

        SCNNode *brick = [SCNNode nodeWithGeometry:box];

        brick.name = @”brick”;

        brick.physicsBody = [SCNPhysicsBody dynamicBody];

        brick.physicsBody.angularVelocityFactor = SCNVector3Make(0, 0, 0);

        brick.position = SCNVector3Make(x, y, 0);

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * i * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            [self.sceneView.scene.rootNode addChildNode:brick];

        });

    }

}

– (void)createLight {

    SCNLight *light = [SCNLight light];

    light.type = SCNLightTypeSpot;

    light.spotInnerAngle = 30.0;

    light.spotOuterAngle = 80.0;

    light.castsShadow = YES;

    light.shadowColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];

    SCNNode *lightNode = [SCNNode node];

    lightNode.light = light;

    lightNode.position = SCNVector3Make(0, 30, 10);

    lightNode.rotation = SCNVector4Make(1, 0, 0, –M_PI * 0.45);

    [self.sceneView.scene.rootNode addChildNode:lightNode];

}

– (void)createCamera {

    SCNNode *camera = [SCNNode node];

    camera.camera = [SCNCamera camera];

    camera.position = SCNVector3Make(0, 4, 20);

    [self.sceneView.scene.rootNode addChildNode:camera];

}

– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    CGPoint p = [[touches anyObject] locationInView:self.sceneView];

    SCNHitTestResult *n = [self.sceneView hitTest:p options:@{SCNHitTestSortResultsKey : @YES}].firstObject;

    if ([n.node.name isEqual:@”brick”]) {

        [n.node runAction:[SCNAction moveByX:0 y:0 z:-3 duration:1.0]];

    }

}

@end