ページ

2012年8月5日日曜日

当たり判定で遊んでみる

Objective-Cで当たり判定で遊んでみたくなったのでちょっと作ってみました。

完成図



ちょっと分かりづらいですが画像のように緑の枠の中に対象の画像が重なると何かしらのアクションを起こします。今回はログを出力するだけにしています。

はじめ

あたり判定にはCGRectIntersectsRectメソッドを使用しました。
このCGRectIntersectsRectはオブジェクトとオブジェクトが重なり合ったときに呼ばれるものでゲーム制作なんかにも使用されてるみたいです。CGRectIntersectsRectに関しては以下を参考にしました。

cocos2dでCCSpriteなどの矩形の衝突判定 - なんかもう実験場

開発環境、プロジェクト

開発環境は、Xcode4.3.3、エミュレータはiPhone iOS5.1です。プロジェクトは「Single View Application」を選択。

ソースコード

今回は画像のドラッグは「ImageDragView」というクラスを作りそこで管理しています。

ViewController

とりあえずはじめにビューと画像の表示から。

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{
    UIView *_viewA;  //目標ビュー
}

@end

ViewController.m

#import "ImageDragView.h"

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //目標ビュー
    _viewA = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 150, 200)];
    _viewA.backgroundColor = [UIColor greenColor];
    [self.view addSubview:_viewA];
    
    //画像1
    ImageDragView *image = [[ImageDragView alloc] initWithImage:[UIImage imageNamed:@"xbox.png"]];
    image.frame = CGRectMake(50, 300, image.frame.size.width, image.frame.size.height);
    image.userInteractionEnabled = YES;
    [self.view addSubview:image];
    [image release];
    
    //画像2 なんとなく2個作る
    ImageDragView *image2 = [[ImageDragView alloc] initWithImage:[UIImage imageNamed:@"xbox.png"]];
    image2.frame = CGRectMake(140, 300, image2.frame.size.width, image2.frame.size.height);
    image2.userInteractionEnabled = YES;
    [self.view addSubview:image2];
    [image2 release];
}

ImageDragView

次に画像のドラッグを管理するImageDragViewです。

ImageDragView.h

#import <UIKit/UIKit.h>

@interface ImageDragView : UIImageView{
    CGPoint touchBeganPoint;
}

@end

ImageDragView.m

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    touchBeganPoint = [[touches anyObject] locationInView:self];
}

- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    CGPoint point = [[touches anyObject] locationInView:self];
    CGRect frame = [self frame];
    frame.origin.x += point.x - touchBeganPoint.x;
    frame.origin.y += point.y - touchBeganPoint.y;
    [self setFrame:frame];
    
    //目標ビューと同じ大きさのビューを作成
    UIView *viewAField = [[UIView alloc]initWithFrame:CGRectMake(10, 10, 150, 200)];
    //ビューと画像が重なり合ったか判定
    if (CGRectIntersectsRect(self.frame, viewAField.frame)) {
        NSLog(@"do do しようぜ!");
    }
    [viewAField release];
}

目標ビューと同じ大きさのビューをここで作っているのですがもう少し上手いことできないものかと。もう少しスマートに書けそうですね・・・。

おわり

当たり判定なんですがこちら記事によると何種類かあるみたいです。

こういったビューや画像を動かしてごにょごにょするっていう動作はカメラ系(特に以下のようなデコる系)のアプリではおなじみの処理っぽいですが、でも実際はどうなんでしょう。

DecoAlbum -プリクラ系デコレーションアプリデコアルバム- 1.0.2(無料)App
カテゴリ: 写真/ビデオ, ソーシャルネットワーキング
販売元: Prime Again Co., Ltd. - Prime Again Co., Ltd.(サイズ: 38.8 MB)


今回のサンプル

CollisionTest - GitHub

参考記事

[iPhone 開発メモ] 画像をドラッグする - Sun Limited Mt.
Drag an Image within the Bounds of Superview - Mobile Developer Tips

0 件のコメント:

コメントを投稿