ボールをポンポンと上に進めていくゲームのサンプル
(XcodeのiOS6 Simulatorで試しています。)
ポイント
・タッチしたとことにブロックを作る
・ボールはブロックにぶつかると跳ねるようにする
サンプル
#import “ViewController.h”
#import <QuartzCore/QuartzCore.h>
typedef struct {
float x, y; // 座標
float vx, vy; // 速さ
} BallData;
@interface ViewController () {
UIView *ballView;
BallData ballData;
CADisplayLink *timer;
NSMutableArray *markers;
}
@end
@implementation ViewController
– (void)viewDidLoad
{
[super viewDidLoad];
[self createBall];
[self start];
markers = [[NSMutableArray alloc] init];
}
– (void)viewDidDisappear:(BOOL)animated
{
[timer invalidate];
timer = nil;
markers = nil;
}
– (void)createBall
{
// data
ballData.x = 160.0;
ballData.y = 240.0;
ballData.vx = 0;
ballData.vy = 0;
// view
ballView = [[UIView alloc] initWithFrame:CGRectMake(160, 240, 20, 20)];
ballView.backgroundColor = [UIColor yellowColor];
ballView.layer.cornerRadius = 10.0;
[self.view addSubview:ballView];
}
– (void)start
{
timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateDisplay:)];
[timer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}
– (void)updateDisplay:(CADisplayLink*)sender
{
// update ball
[self updateBall:sender.duration];
// collision
[self checkCollision];
}
– (void)updateBall:(float)duration
{
float g = 9.8 * 100;
ballData.y += ballData.vy * duration + 0.5 * g * powf(duration, 2.0);
ballData.vy += g * duration;
ballData.x += ballData.vx * duration;
ballView.center = CGPointMake(ballData.x, ballData.y);
}
– (void)checkCollision
{
// 画面の端っこにきたら跳ね返す
if (ballData.y >= 470) {
ballData.vy = – abs(ballData.vy);
} else if (ballData.x >= 320) {
ballData.vx = – abs(ballData.vx);
} else if (ballData.x <= 0) {
ballData.vx = abs(ballData.vx);
}
// マーカーにぶつかったときの挙動
for (UIView *mark in markers) {
if(CGRectIntersectsRect(ballView.frame, mark.frame)) {
float dx = ballView.center.x – mark.center.x;
float dy = ballView.center.y – mark.center.y;
ballData.vx = dx * 10;
ballData.vy = dy * 10 – 200;
}
}
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *t = [touches anyObject];
CGPoint p = [t locationInView:self.view];
UIView *mark = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
mark.layer.cornerRadius = 5.0;
mark.backgroundColor = [UIColor greenColor];
mark.center = p;
[self.view addSubview:mark];
[markers addObject:mark];
}
– (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end