iPhone皮むき

ボールを皮で包んで剥いてといったiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@import SceneKit;

@interface ViewController ()

@property (nonatomic, weak) SCNView *sceneView;

@property (nonatomic) BOOL on;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    [self setupScene];

    [self createEgg];

    [self createShell];

    [self createCamera];

}

– (void)setupScene {

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

    sv.scene = [SCNScene scene];

    sv.backgroundColor = [UIColor lightGrayColor];

    sv.autoenablesDefaultLighting = YES;

    sv.allowsCameraControl = YES;

    [self.view addSubview:sv];

    

    self.sceneView = sv;

}

– (void)createEgg {

    SCNSphere *s = [SCNSphere sphereWithRadius:10];

    s.firstMaterial.diffuse.contents = [UIColor colorWithHue:0.1 saturation:0.02 brightness:1 alpha:1];

    SCNNode *sn = [SCNNode nodeWithGeometry:s];

    sn.name = @”egg”;

    sn.transform = SCNMatrix4Scale(sn.transform, 1, 1, 1);

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

}

– (void)createShell {

    

    SCNNode *egg = [self.sceneView.scene.rootNode childNodeWithName:@”egg” recursively:NO];

    

    float r = 10.2;

    float dw = M_PI / 50.0;

    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointZero radius:r startAngle:0 endAngle:M_PI clockwise:NO];

    path.flatness = 0.2;

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

        SCNShape *shape = [SCNShape shapeWithPath:path extrusionDepth:0.8];

        shape.firstMaterial.diffuse.contents = [UIColor colorWithHue:0.1 saturation:0.3 brightness:0.8 alpha:1];

        SCNNode *shapeNode = [SCNNode nodeWithGeometry:shape];

        shapeNode.name = [NSString stringWithFormat:@”shell %d”, i];

        shapeNode.rotation = SCNVector4Make(1, 0, 0, dw * i);

        [egg addChildNode:shapeNode];

    }

}

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

    

    self.on = !self.on;

    float dw = M_PI / 50.0;

    

    NSArray *shell = [self.sceneView.scene.rootNode childNodeWithName:@”egg” recursively:NO].childNodes;

    for (SCNNode *n in shell) {

        int i = [[n.name componentsSeparatedByString:@” “][1] intValue];

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

            if (self.on) {

                [n runAction:[SCNAction rotateToX:0 y:0 z:0 duration:0.5]];

            } else {

                [n runAction:[SCNAction rotateToX:dw * i y:0 z:0 duration:0.5]];

            }

        });

    }

}

– (void)createCamera {

    SCNNode *camera = [SCNNode node];

    camera.camera = [SCNCamera camera];

    camera.position = SCNVector3Make(0, 0, 50);

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

}

@end