iPhone簡易モーフィング

球体を平べったい板に変形させるiPhoneアプリのサンプルコード

#import “ViewController.h”

@import SceneKit;

@interface ViewController ()

@property (nonatomic, weak) SCNView *sceneView;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    [self setupScene];

    [self createObjectWithMorph];

    [self createCamera];

}

– (void)setupScene {

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

    sv.scene = [SCNScene scene];

    sv.backgroundColor = [UIColor grayColor];

    sv.allowsCameraControl = YES;

    sv.autoenablesDefaultLighting = YES;

    [self.view addSubview:sv];

    

    self.sceneView = sv;

}

– (void)createObjectWithMorph {

    SCNBox *box = [SCNBox boxWithWidth:3 height:3 length:3 chamferRadius:1.5];

    box.firstMaterial.diffuse.contents = [UIColor orangeColor];

    box.chamferSegmentCount = 50;

    SCNNode *boxNode = [SCNNode nodeWithGeometry:box];

    boxNode.name = @”obj”;

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

    

    SCNMorpher *mopher = [[SCNMorpher alloc] init];

    SCNBox *box2 = [SCNBox boxWithWidth:3 height:10 length:1 chamferRadius:1.5];

    box2.chamferSegmentCount = 50;

    

    SCNBox *box3 = [SCNBox boxWithWidth:10 height:1 length:3 chamferRadius:1.5];

    box3.chamferSegmentCount = 50;

    

    // they must contain the same number and structural arrangement of vertices.

    mopher.targets = @[box2, box3];

    boxNode.morpher = mopher;

}

– (void)createCamera {

    SCNNode *camera = [SCNNode node];

    camera.camera = [SCNCamera camera];

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

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

}

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

{

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

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        CABasicAnimation *a1 = [CABasicAnimation animationWithKeyPath:@”morpher.weights[0]”];

        a1.fromValue = @0.0;

        a1.toValue = @1.0;

        a1.autoreverses = YES;

        a1.duration = 0.5;

        

        CABasicAnimation *a2 = [CABasicAnimation animationWithKeyPath:@”morpher.weights[1]”];

        a2.fromValue = @0.0;

        a2.toValue = @1.0;

        a2.duration = 0.5;

        a2.beginTime = 1.0;

        a2.autoreverses = YES;

        

        CAAnimationGroup *group = [CAAnimationGroup animation];

        group.animations = @[a1, a2];

        group.duration = 2.0;

        group.repeatCount = 100;

        

        [obj addAnimation:group forKey:nil];

    });

}

@end