くるくる回っている30個のダイアルをマーカーのところで止めていく単純なiPhoneゲームを書いてみます。
動作イメージ
XcodeからiOS6 iPhone Simulatorで動かすとこんな感じになります。
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
@property (strong, nonatomic) NSMutableArray *dials;
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor greenColor];
[self createDials];
[self createTargetMark];
[self startTimer];
}
– (void)createDials
{
for (int i=0; i<30; i++) {
float x = (i % 5) * 60 + 40;
float y = (i / 5) * 60 + 80;
UIView *d = [self createDial];
d.center = CGPointMake(x, y);
}
}
– (void)createTargetMark
{
for (int i=0; i<30; i++) {
float x = (i % 5) * 60 + 40;
float y = (i / 5) * 60 + 80;
UIView *mark = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 8, 8)];
mark.backgroundColor = [UIColor whiteColor];
mark.layer.cornerRadius = 4;
float angle = (arc4random() % 10) * M_PI / 5.0;
float r = 25.0;
float x1 = r * cos(angle);
float y1 = r * sin(angle);
mark.center = CGPointMake(x + x1, y + y1);
[self.view addSubview:mark];
}
}
– (UIView *)createDial
{
UIView *dial = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
dial.layer.cornerRadius = 25;
dial.layer.borderColor = [UIColor grayColor].CGColor;
dial.layer.borderWidth = 3;
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:CGPointMake(25, 8)];
[path addLineToPoint:CGPointMake(25, 45)];
[path moveToPoint:CGPointMake(20, 40)];
[path addLineToPoint:CGPointMake(25, 45)];
[path addLineToPoint:CGPointMake(30, 40)];
CAShapeLayer *sl = [CAShapeLayer layer];
sl.path = path.CGPath;
sl.fillColor = [UIColor clearColor].CGColor;
sl.strokeColor = [UIColor redColor].CGColor;
sl.lineWidth = 3;
[dial.layer addSublayer:sl];
[self.view addSubview:dial];
[self.dials addObject:dial];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
[dial addGestureRecognizer:tap];
return dial;
}
– (void)tap:(UITapGestureRecognizer*)gr
{
gr.view.tag = (gr.view.tag + 1) % 2;
}
– (void)startTimer
{
[NSTimer scheduledTimerWithTimeInterval:1.5/60.0 target:self selector:@selector(tick:) userInfo:nil repeats:YES];
}
– (void)tick:(NSTimer *)sender
{
for (UIView *v in self.dials) {
if (v.tag == 0) {
v.transform = CGAffineTransformRotate(v.transform, M_PI/60.0);
}
}
}
– (NSMutableArray *)dials
{
if (!_dials) {
_dials = [[NSMutableArray alloc] init];
}
return _dials;
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end