ブロック崩しのボールが跳ね返らないやつです。
ボタンを押せばランダムな方向に、鉄球が飛んでいき、
ぶつかったものを容赦なく消し去る感じに仕上げています。

ポイント
ボールの判定は、CGRectIntersectsRectをつかって、
ブロックとぶつかると、ブロック消滅、ボールはそのまま直進
あとは、ボールの座標をみて、画面の外に出ていたら、
次弾の発射を可能とする。と言った感じにしました。

環境

今回つくったiPhoneアプリサンプルは、

XcodeのiOS6 iPhone Simulatorで動かしています。


サンプルコード

#import “ViewController.h”

#import <QuartzCore/QuartzCore.h>

@interface ViewController () {

    UIView *ball;

    CGPoint velocity;

    NSTimer *timer;

}

@end

@implementation ViewController

– (void)viewDidLoad

{

    [super viewDidLoad];

    

    [self createBlocks];

    

    [self createShooter];

    

    [self start];

}

– (void)createBlocks

{

    for (int i=0; i<150; i++) {

        float x = (i % 10) * 32;

        float y = (i / 10) * 20;

        UIView *block = [[UIView alloc] initWithFrame:CGRectMake(x, y, 32, 20)];

        

        float num = arc4random() % 10;

        block.backgroundColor = [UIColor colorWithHue:1.0/num saturation:1 brightness:1 alpha:1];

        block.layer.borderColor = self.view.backgroundColor.CGColor;

        block.layer.borderWidth = 1;

        block.tag = 10;

        [self.view addSubview:block];

    }

}

– (void)createShooter

{

    UIView *shooter = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];

    shooter.center = CGPointMake(160, 400);

    shooter.backgroundColor = [UIColor whiteColor];

    shooter.layer.cornerRadius = 5.0;

    [self.view addSubview:shooter];

    

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];

    [shooter addGestureRecognizer:tap];

}

– (void)tap

{

    if (!ball) {

        ball = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];

        ball.backgroundColor = [UIColor blackColor];

        ball.center = CGPointMake(160, 400);

        ball.layer.cornerRadius = 10;

        [self.view addSubview:ball];

        

        float range = (arc4random() % 10) * M_PI * 0.05 + M_PI * 0.25;

        velocity = CGPointMake(20 * cos(range), 20 * sin(range));

    }

}

– (void)start

{

    timer = [NSTimer scheduledTimerWithTimeInterval:1.0/60.0 target:self selector:@selector(tick:) userInfo:nil repeats:YES];

}

– (void)tick:(NSTimer*)sender

{

    if (ball) {

        ball.center = CGPointMake(ball.center.x + velocity.x, ball.center.yvelocity.y);

        for (UIView *block in self.view.subviews) {

            if (block.tag == 10) {

                if (CGRectIntersectsRect(block.frame, ball.frame)) {

                    [block removeFromSuperview];

                }

            }

        }

        if (ball.center.y < 0 || ball.center.x < 0 || ball.center.x > 320) {

            [ball removeFromSuperview];

            ball = nil;

        }

    }

}

– (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end