発射台をタッチしてカラーボールをポンポンと飛ばして遊ぶ簡単なiPhoneゲームを描いてみます。
動作イメージ
XcodeからiOS6 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController () {
UIView *catapult;
float angle;
BOOL speedup;
}
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor blackColor];
[self createCatapult];
[self start];
}
#define Center CGPointMake(160, 250)
– (void)createCatapult
{
catapult = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
catapult.layer.cornerRadius = 10;
catapult.backgroundColor = [UIColor whiteColor];
catapult.center = CGPointMake(Center.x, Center.y – 60);
[self.view addSubview:catapult];
UIView *rail = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 120)];
rail.center = Center;
rail.backgroundColor = [UIColor colorWithWhite:1 alpha:0.2];
rail.layer.borderColor = [UIColor whiteColor].CGColor;
rail.layer.borderWidth = 1;
rail.layer.cornerRadius = 60;
[self.view addSubview:rail];
UILongPressGestureRecognizer *lp = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(press:)];
lp.minimumPressDuration = 0;
[rail addGestureRecognizer:lp];
}
– (void)press:(UILongPressGestureRecognizer*)gr
{
if (gr.state == UIGestureRecognizerStateBegan) {
CABasicAnimation *twinkle = [CABasicAnimation animationWithKeyPath:@”opacity”];
twinkle.toValue = @0.5;
twinkle.duration = 0.5;
twinkle.autoreverses = YES;
twinkle.repeatCount = 100;
[catapult.layer addAnimation:twinkle forKey:nil];
speedup = YES;
}
if (gr.state == UIGestureRecognizerStateEnded) {
[catapult.layer removeAllAnimations];
[self shot];
speedup = NO;
}
}
– (void)shot
{
UIView *bullet = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
float hue = (arc4random() % 10) * 0.1;
bullet.backgroundColor = [UIColor colorWithHue:hue saturation:1 brightness:1 alpha:1];
bullet.center = catapult.center;
bullet.layer.cornerRadius = 5.0;
[self.view addSubview:bullet];
[UIView animateWithDuration:15.0 animations:^{
float x = Center.x + 300.0 * cos(angle);
float y = Center.y + 300.0 * sin(angle);
bullet.center = CGPointMake(x, y);
} completion:^(BOOL finished) {
[bullet removeFromSuperview];
}];
}
– (void)start
{
[NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:@selector(tick:) userInfo:nil repeats:YES];
}
– (void)tick:(NSTimer*)sender
{
angle += sender.timeInterval;
if (speedup) {
angle += sender.timeInterval * 2.0;
}
float x = Center.x + 60.0 * cos(angle);
float y = Center.y + 60.0 * sin(angle);
catapult.center = CGPointMake(x, y);
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end