iPhone6色キューブ

SceneKitで6色のキューブを表示するiPhoneアプリのサンプルコードを描いてみます。

#import “ViewController.h”

@import SceneKit;

@interface ViewController ()

@property (nonatomic, weak) SCNScene *scene;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    

    SCNView *sceneView = [[SCNView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)];

    sceneView.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));

    sceneView.backgroundColor = [UIColor orangeColor];

    [self.view addSubview:sceneView];

    

    SCNScene *scene = [SCNScene scene];

    sceneView.scene = scene;

    self.scene = scene;

    

    

    float s = 10;

    SCNBox *box =[SCNBox boxWithWidth:s height:s length:s chamferRadius:0.1];

    

    NSMutableArray *materials = [@[] mutableCopy];

    NSArray *parts = @[[self imageWithColor:[UIColor redColor]],

                       [self imageWithColor:[UIColor blueColor]],

                       [self imageWithColor:[UIColor greenColor]],

                       [self imageWithColor:[UIColor purpleColor]],

                       [self imageWithColor:[UIColor brownColor]],

                       [self imageWithColor:[UIColor yellowColor]]];

    for (id part in parts) {

        SCNMaterial *material = [SCNMaterial material];

        material.diffuse.contents = part;

        [materials addObject:material];

    }

    

    SCNNode *cube = [SCNNode node];

    cube.name = @”cube”;

    cube.geometry = box;

    cube.geometry.materials = materials;

    [scene.rootNode addChildNode:cube];

    

    SCNNode *cameraNode = [SCNNode node];

    cameraNode.camera = [SCNCamera camera];;

    cameraNode.position = SCNVector3Make(0, 0, 40);

    [scene.rootNode addChildNode:cameraNode];

    

    UILabel *title = [[UILabel alloc] init];

    title.text = @”Cube Rotation”;

    title.textColor = [UIColor whiteColor];

    [title sizeToFit];

    title.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.frame) + 100);

    [self.view addSubview:title];

}

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

{

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

    [SCNTransaction begin];

    [SCNTransaction setAnimationDuration:0.5];

    cube.transform = SCNMatrix4Rotate(cube.transform, M_PI/3.0, 0, 1, 0.4);

    [SCNTransaction commit];

}

– (UIImage *)imageWithColor:(UIColor *)color

{

    CGRect rect = CGRectMake(0, 0, 1, 1);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(ctx, color.CGColor);

    CGContextFillRect(ctx, rect);

    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    

    return img;

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

}

@end