iPhoneワイヤー幾何模様

ワイヤーを回して幾何模様をつくるiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@import SceneKit;

@interface ViewController ()

@property (nonatomic) NSUInteger count;

@property (nonatomic, weak) SCNView *sceneView;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    [self setupScene];

    [self createRect];

    [self createCamera];

}

– (void)setupScene {

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

    sv.backgroundColor = [UIColor orangeColor];

    sv.scene = [SCNScene scene];

    sv.autoenablesDefaultLighting = YES;

    sv.allowsCameraControl = YES;

    [self.view addSubview:sv];

    

    self.sceneView = sv;

}

– (void)createRect {

    

    for (NSString *name in @[@”rectA”, @”rectB”]) {

        SCNNode *rect = [SCNNode node];

        rect.name = name;

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

            SCNBox *pipe = [SCNBox boxWithWidth:20 height:0.5 length:0.5 chamferRadius:0.25];

            pipe.firstMaterial.diffuse.contents = [UIColor colorWithWhite:0.98 alpha:1];

            SCNNode *pipeNode = [SCNNode nodeWithGeometry:pipe];

            pipeNode.pivot = SCNMatrix4MakeTranslation(0, 9.75, 0);

            pipeNode.rotation = SCNVector4Make(0, 0, 1, i * M_PI * 0.5);

            [rect addChildNode:pipeNode];

        }

        

        rect.position = SCNVector3Make([name isEqual:@”rectA”] ? –15 : 15, 0, 0);

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

    }

}

– (void)createCamera {

    SCNNode *camera = [SCNNode node];

    camera.camera = [SCNCamera camera];

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

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

}

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

    

    if (self.count > 0) {

        return;

    }

    [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(turn:) userInfo:nil repeats:YES];

}

– (void)turn:(NSTimer *)timer {

    float dw = M_PI / 20.0;

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

    SCNNode *newRect = [rect clone]; // copy

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

    [rect runAction:[SCNAction rotateByAngle:dw aroundAxis:SCNVector3Make(0, 0, 1) duration:0.2]];

    

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

    SCNNode *newRectB = [rectB clone]; // copy

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

    [rectB runAction:[SCNAction rotateByAngle:2.0 * dw aroundAxis:SCNVector3Make(1, 0, 1) duration:0.2]];

    

    self.count++;

    if (self.count > 20) {

        [timer invalidate];

    }

}

@end