iPhoneペダル

ペダルをクルクル回すiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@import SceneKit;

@interface ViewController ()

@property (nonatomic, weak) SCNView *sceneView;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    [self setupScene];

    [self createBicycle];

    [self createCamera];

}

– (void)setupScene {

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

    sv.scene = [SCNScene scene];

    sv.backgroundColor = [self color:4];

    sv.allowsCameraControl = YES;

    [self.view addSubview:sv];

    

    self.sceneView = sv;

}

– (void)createBicycle {

    SCNBox *body = [SCNBox boxWithWidth:20 height:5 length:0.1 chamferRadius:0];

    body.firstMaterial.diffuse.contents = [[self color:2] colorWithAlphaComponent:0.8];

    SCNNode *bodyNode = [SCNNode nodeWithGeometry:body];

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

    

    SCNShape *gear = [SCNShape shapeWithPath:[UIBezierPath bezierPathWithArcCenter:CGPointZero radius:2 startAngle:0 endAngle:2.0 * M_PI clockwise:NO] extrusionDepth:0.2];

    gear.firstMaterial.diffuse.contents = [self color:1];

    SCNNode *gearNode = [SCNNode nodeWithGeometry:gear];

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

    

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

        SCNBox *pedal = [SCNBox boxWithWidth:1 height:0.4 length:1.6 chamferRadius:0];

        pedal.firstMaterial.diffuse.contents = [self color:0];

        SCNNode *pedalNode = [SCNNode nodeWithGeometry:pedal];

        pedalNode.position = SCNVector3Make(i==0 ? –2 : 2, 0, i==0 ? –1 : 1);

        [gearNode addChildNode:pedalNode];

    }

    

    [gearNode runAction:[SCNAction repeatActionForever:[SCNAction rotateByAngle:M_PI aroundAxis:SCNVector3Make(0, 0, 1) duration:1.0]]];

}

– (void)createCamera {

    SCNNode *camera = [SCNNode node];

    camera.camera = [SCNCamera camera];

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

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

}

#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 colorCode[] = {0x222130, 0x464D57, 0xD4E8D3, 0xFFFCFB, 0xED8917};

    return ColorHex(colorCode[i]);

}

@end