iPhoneしましまオブジェ

縞模様の棒をつかって、しましまなオブジェを表示するiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@import SceneKit;

@interface ViewController () <SCNSceneRendererDelegate>

@property (nonatomic, weak) SCNView *sceneView;

@property (nonatomic) BOOL turn;

@property (nonatomic) BOOL start;

@property (nonatomic) int counter;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    [self setupScene];

    [self createBar];

    [self createCamera];

}

– (void)setupScene {

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

    sv.backgroundColor = [UIColor colorWithWhite:0.05 alpha:1];

    sv.scene = [SCNScene scene];

    sv.scene.physicsWorld.gravity = SCNVector3Zero;

    sv.allowsCameraControl = YES;

    sv.autoenablesDefaultLighting = YES;

    sv.delegate = self;

    [self.view addSubview:sv];

    

    self.sceneView = sv;

}

– (void)createBar {

    SCNNode *sBar = [SCNNode node];

    sBar.name = @”bar”;

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

    

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

        SCNCylinder *c = [SCNCylinder cylinderWithRadius:0.2 height:0.2];

        c.firstMaterial.diffuse.contents = [UIColor colorWithHue:0.35 saturation:0.4 brightness:1 alpha:1];

        SCNNode *cNode = [SCNNode nodeWithGeometry:c];

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

        cNode.position = SCNVector3Make(i * 0.4, 0, 0);

        [sBar addChildNode:cNode];

    }

    

    sBar.physicsBody = [SCNPhysicsBody dynamicBody];

}

– (void)createCamera {

    SCNNode *camera = [SCNNode node];

    camera.camera = [SCNCamera camera];

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

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

}

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

    if (!self.start) {

        self.start = YES;

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

            self.start = NO;

        });

    }

    self.turn = YES;

}

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

    self.turn = NO;

}

– (void)renderer:(id<SCNSceneRenderer>)aRenderer updateAtTime:(NSTimeInterval)time {

    

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

    if (!self.start) {

        bar.physicsBody.velocity = SCNVector3Make(0, 0, 0);

        return;

    }

    

    bar.physicsBody.velocity = SCNVector3Make(0, –1, 0);

    if (self.turn) {

        bar.physicsBody.angularVelocity = SCNVector4Make(0, 1, 0, 1);

    } else {

        bar.physicsBody.angularVelocity = SCNVector4Zero;

    }

    

    if (self.counter == 5) {

        SCNNode *barClone = bar.presentationNode.clone;

        barClone.physicsBody = nil;

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

        self.counter = 0;

    }

    self.counter++;

}

@end