Cocos2d Tiledを使ってみる 第2回

前回行ったTiledの2つ目のチュートリアル。 今回は、衝突を判定して処理をする。例えば、壁にぶつかったり、敵に当たったり、アイテムを取得したりなどの処理が作れます。

またまたこのサイト→RayWenderlichチュートリアルです。

少し前回の復習

1、Tiledで作ったマップは「CCTMXTiledMapクラス」を使って読み込みます。 2、読み込んだマップのレイアーを取得する際には「CCTMXTiledMapクラスのlayerNamedメソッド」で取得します。 3、個別のオブジェクトを取り出す場合は「objectNamed」「objectGroupNamed」などを使う」

[cpp 1="=" 2="[CCTMXTiledMap" 3="3="tiledMapWithTMXFile:@"TileMap.tmx""" language="self.tileMap"]; // 1 self.background = [tileMap layerNamed:@"Background"]; //2 CCTMXObjectGroup *objects = [tileMap objectGroupNamed:@"objects"]; //3 NSAssert(objects != nil, @"'objects' object grounp not found");

    NSMutableDictionary *spawnPoint = [objects objectNamed:@"SpawnPoint"];  //3
    NSAssert(spawnPoint != nil, @"'SpawnPoint' object grounp not found");

    int x = [[spawnPoint valueForKey:@"x"] intValue];
    int y = [[spawnPoint valueForKey:@"y"] intValue];


    self.player = [CCSprite spriteWithFile:@"Player.png"];
    _player.position = ccp(x,y);
    [self addChild:_player];

    [self setViewpointCenter:_player.position];



    [self addChild:_tileMap z:-1];

[/cpp]

衝突判定を行うレイアーをTiledで作成する。

新規レイアーをマップに追加をして、判定を行いたいエリアを選択する。 今回の例では、レイアー名「Meta」 タイルは「半透明な赤」、タイルのプロパティは「CollidableがTRUE」

このレイアーを使うには「layerNamedメソッド」で取り出して利用します。

[cpp]

            self.meta = [_tileMap layerNamed:@"Meta"];
    _meta.visible = NO;

[/cpp]

タイルとPlayerの判定を行う

Playerと衝突判定用のタイルがぶつかった時の処理を記入します。

[cpp] // setplayerPositionの中

CGPoint tileCoord = [self tileCoordForPosition:position];

int tileGid = [_meta tileGIDAt:tileCoord]; //タイルの場所
if(tileGid){

    NSDictionary *properties = [_tileMap propertiesForGID:tileGid]; //プロパティがあれば記憶させる
    if(properties){

        NSString *collision = [properties valueForKey:@"Collidable"]; //プロパティを選択
        if(collision && [collision compare:@"True"] == NSOrderedSame){ // 衝突の処理を書く

            [[SimpleAudioEngine sharedEngine] playEffect:@"hit.caf"];

            return;

        }

[/cpp]

今回の例では、playerが重なることができなくて且つ音(hit.caf)が鳴るという処理です。

衝突判定を管理するレイアーのプロパティを追加する

今度はオブジェクトに触れるとそれが、無くなると行った処理を追加します。 TiledのMetaに先ほどのCollidateプロパティ以外のプロパティを設定してやる。

[cpp]

       NSString *collectable = [properties valueForKey:@"Collectable"]; if(collectable && [collectable compare:@"True"] == NSOrderedSame){

            [_meta removeTileAt:tileCoord]; // Meta(衝突を管理するレイアー)が消える
            [_foreground removeTileAt:tileCoord];  //foregroundが消える
        }

[/cpp]

Learn iPhone and iPad cocos2d Game DevelopmentLearn iPhone and iPad cocos2d Game Development
Steffen Itterheim

Apress
売り上げランキング : 39550

Amazonで詳しく見る