小さな水槽をゆびでなぞってみよう。
ゆびで描いた線の上をお魚が泳いでいくよ〜。
という感じのiPhoneゲームのサンプルを作ってみた。

ポイント
魚の画像を、CAKeyframeAnimationを利用することで、
ゆびでなぞった線にそって魚を動かしています。

環境
今回つくったiPhoneアプリサンプルは、
XcodeのiOS6 iPhone Simulatorで動かしています。


サンプルコード


#import “ViewController.h”

#import <QuartzCore/QuartzCore.h>

@interface ViewController () {

    UIBezierPath *path;

    CAShapeLayer *sl;

}

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    [self createPool];

}

– (void)createPool

{

    UIImage *img = [UIImage imageNamed:@”water”];

    UIImageView *background = [[UIImageView alloc] initWithImage:img];

    background.frame = self.view.bounds;

    [self.view addSubview:background];

}

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

{

    CGPoint p = [[touches anyObject] locationInView:self.view];

    

    path = [[UIBezierPath alloc] init];

    [path moveToPoint:p];

    

    sl = [[CAShapeLayer alloc] initWithLayer:self.view.layer];

    sl.fillColor = [UIColor clearColor].CGColor;

    sl.strokeColor = [UIColor blueColor].CGColor;

    sl.lineWidth = 5;

    sl.lineDashPattern = [NSArray arrayWithObjects:@5, @5,nil];

    [self.view.layer addSublayer:sl];

}

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

{

    CGPoint p = [[touches anyObject] locationInView:self.view];

    [path addLineToPoint:p];

    sl.path = path.CGPath;

}

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

{

    UIImage *fishImg = [UIImage imageNamed:@”fish”];

    UIImageView *fish = [[UIImageView alloc] initWithImage:fishImg];

    [self.view addSubview:fish];

    

    CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@”position”];

    anim.path = path.CGPath;

    anim.rotationMode = kCAAnimationRotateAutoReverse;

    anim.repeatCount = HUGE_VALF;

    anim.duration = 10.0;

    [fish.layer addAnimation:anim forKey:@”swim”];

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end