前回行ったTiledの2つ目のチュートリアル。
今回は、衝突を判定して処理をする。例えば、壁にぶつかったり、敵に当たったり、アイテムを取得したりなどの処理が作れます。
またまたこのサイト→RayWenderlichのチュートリアルです。
少し前回の復習
1、Tiledで作ったマップは「CCTMXTiledMapクラス」を使って読み込みます。
2、読み込んだマップのレイアーを取得する際には「CCTMXTiledMapクラスのlayerNamedメソッド」で取得します。
3、個別のオブジェクトを取り出す場合は「objectNamed」「objectGroupNamed」などを使う」
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
; // 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]; |
衝突判定を行うレイアーをTiledで作成する。
新規レイアーをマップに追加をして、判定を行いたいエリアを選択する。
今回の例では、レイアー名「Meta」 タイルは「半透明な赤」、タイルのプロパティは「CollidableがTRUE」

このレイアーを使うには「layerNamedメソッド」で取り出して利用します。
1 2 |
self.meta = [_tileMap layerNamed:@"Meta"]; _meta.visible = NO; |
タイルとPlayerの判定を行う
Playerと衝突判定用のタイルがぶつかった時の処理を記入します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// 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; } |
今回の例では、playerが重なることができなくて且つ音(hit.caf)が鳴るという処理です。
衝突判定を管理するレイアーのプロパティを追加する
今度はオブジェクトに触れるとそれが、無くなると行った処理を追加します。
TiledのMetaに先ほどのCollidateプロパティ以外のプロパティを設定してやる。
1 2 3 4 5 6 |
NSString *collectable = [properties valueForKey:@"Collectable"]; if(collectable && [collectable compare:@"True"] == NSOrderedSame){ [_meta removeTileAt:tileCoord]; // Meta(衝突を管理するレイアー)が消える [_foreground removeTileAt:tileCoord]; //foregroundが消える } |
![]() | Learn iPhone and iPad cocos2d Game Development Steffen Itterheim Apress 売り上げランキング : 39550 Amazonで詳しく見る |
