引っぱると、はんたいの方向に車が飛んでいくよ!
黄色い四角をたくさんGetしよう!
という感じの子供向けiPhoneゲームのサンプルを書いてみた。
ポイント
PanGestureRecognizerのなかで、引っぱってる角度を計算、
その方向に車Viewのtransform rotationを設定しておき、
離したときに、transform translateでy方向を増加させておくことで、
引っぱったのと反対に車を動かしてます。
環境
今回つくったiPhoneアプリサンプルは、
XcodeのiOS6 iPhone Simulatorで動かしています。
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController () {
UIImageView *car;
float energy;
}
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor darkGrayColor];
UIView *whiteLine = [[UIView alloc] initWithFrame:CGRectMake(155, 0, 10, 500)];
whiteLine.backgroundColor = [UIColor whiteColor];
[self.view addSubview:whiteLine];
[self createCar];
[self startJackPot];
}
– (void)createCar
{
UIImage *carImg = [UIImage imageNamed:@”car”];
car = [[UIImageView alloc] initWithImage:carImg];
car.center = CGPointMake(160, 240);
[self.view addSubview:car];
car.userInteractionEnabled = YES;
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pull:)];
[car addGestureRecognizer:pan];
}
– (void)pull:(UIPanGestureRecognizer*)gr
{
CGPoint p = [gr locationInView:self.view];
gr.view.center = p;
CGPoint dir = [gr translationInView:self.view];
float angle = atan2f(-dir.x, dir.y);
gr.view.transform = CGAffineTransformMakeRotation(angle);
if (gr.state == UIGestureRecognizerStateEnded) {
energy = hypotf(dir.x, dir.y);
[NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:@selector(drive:) userInfo:nil repeats:YES];
}
}
– (void)drive:(NSTimer*)sender{
if (energy < 0) {
[sender invalidate];
[car removeFromSuperview];
[self createCar];
}
energy–;
float velocity = energy * energy / 1000.0;
car.transform = CGAffineTransformTranslate(car.transform, 0, -velocity);
// collision check
CGRect check = [car.layer.presentationLayer frame];
for (UIView *v in self.view.subviews) {
if (v.tag == 1) {
if (CGRectIntersectsRect(check, v.frame)) {
[UIView animateWithDuration:0.3 animations:^{
v.transform = CGAffineTransformMakeScale(3, 3);
v.alpha = 0;
}];
}
}
}
}
– (void)startJackPot
{
for (int i =0; i < 20; i++) {
[self performSelector:@selector(showCoin) withObject:nil afterDelay:i * 2];
}
}
– (void)showCoin
{
float x = arc4random() % 280 + 20;
float y = arc4random() % 100 + 40;
y += (arc4random() % 2) * 270;
UIView *coin = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
coin.backgroundColor = [UIColor yellowColor];
coin.center = CGPointMake(x, y);
coin.tag = 1;
[self.view addSubview:coin];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end