ランダムな横位置から積み木を落とすサンプル
(XcodeのiOS6 Simulatorで試しています。)
ポイント
・一番下まで落ちた、もしくは他のブロックにぶつかったら止める
・隙間をみて楽しむ
サンプルコード
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
typedef enum
{
ObjStop = 0,
ObjDrop,
} ObjStatus;
@interface ViewController () {
CADisplayLink *timer;
}
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
}
– (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self start];
}
– (void)viewDidDisappear:(BOOL)animated
{
[timer invalidate];
timer = nil;
}
– (void)start
{
timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateDisp:)];
[timer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}
– (void)updateDisp:(CADisplayLink*)sender
{
static float lastTime;
if (lastTime > 0.2) {
float x = arc4random() % 300;
UIView *v = [[UIView alloc] initWithFrame:CGRectMake(x, 0, 20, 20)];
v.backgroundColor = [UIColor brownColor];
[self.view addSubview:v];
v.tag = ObjDrop;
lastTime = 0;
}
lastTime += sender.duration;
for (UIView *v in self.view.subviews) {
[self checkBottom:v];
[self checkCollision:v];
if (v.tag == ObjDrop) {
v.center = CGPointMake(v.center.x, v.center.y + 4);
}
}
}
– (void)checkBottom:(UIView*)v
{
if (v.center.y >= self.view.frame.size.height – 20) {
v.tag = ObjStop;
}
}
– (void)checkCollision:(UIView*)v
{
for (UIView *v2 in self.view.subviews) {
if (v2 == v) {
continue;
}
if (CGRectIntersectsRect(v.frame, v2.frame)) {
v.tag = ObjStop;
}
}
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end