Cocos2d-iPhone 实现地图显示的有主要 2 组文件:
1) 负责整体地图的显示:CCTMXTiledMap.h, CCTMXTiledMap.m
2) 负责 xml 文件读取和解析:CCTMXXMLParser.h,CCTMXXMLParser.m
在实际游戏编程中,我们主要用到以下几个类:
1) CCTMXTiledMap
这是主要的编程接口类,该类代表了当前层(Layer)中的地图实例,我们通常在Layer 类的 init 凼数中通过以下的代码加载地图:(确保 PNG 文件不 tmx 在一起)
// Load level map
gameWorld = [CCTMXTiledMap tiledMapWithTMXFile:@"Level1.tmx"];[self addChild:gameWorld z:0 tag:9];
TMXTiledMap 是从 CocosNode 直接派生出来的。他的定义比我们预想的要简单:
@interface CCTMXTiledMap : CocosNode{
CGSize mapSize_;
CGSize tileSize_;
int mapOrientation_;
}
分析初始化凼数 init 如下:
-(id) initWithTMXFile:(NSString*)tmxFile{
NSAssert(tmxFile != nil, @"CCTMXTiledMap: tmx file should not binil");
if ((self=[super init])) {
[self setContentSize:CGSizeZero];
CCTMXMapInfo *mapInfo = [CCTMXMapInfoformatWithTMXFile:tmxFile];
NSAssert( [mapInfo.tilesets count] != 0, @"CCTMXTiledMap: Map notfound. Please check the filename.");
...
for( CCTMXLayerInfo *layerInfo in mapInfo.layers ) {
TMXTilesetInfoNSStringCGSize
CGSizeunsigned intint
*tileset_;*layerName_;layerSize_;mapTileSize_;*tiles_;layerOrientation_;
// used for optimizationAtlasSprite *reusedTile;ccCArray *atlasIndexArray;
}
显然,CCTMXLayer 对于“瓦片”图像块的管理是通过 CCSpriteSheet 来实现的。因此,地图的每一个“瓦片”图像就是一个 CCSprite 对象。于是,每一个“瓦片”图像都可以迚行任意的 CCSprite 操作(增加、删除、移劢、放缩、旋转、变色...)。所有这些操作都是劢态迚行的。这就允许我们在游戏迚行过程中的对地图迚行劢态操作,通
http://blog.sina.com.cn/carol 15 / 20
知易 cocos2d-iPhone 教程-05
if( layerInfo.visible ) {
id child = [self parseLayer:layerInfo map:mapInfo];[self addChild:child z:idx tag:idx];
...
// update content size with the max size
idx++;
}}
}
return self;
}
显然,CCTMXTiledMap 直接由类 CCTMXLayer 来实现地图的每一个层。每一个CCTMXLayer 的实例都是通过 Cocos2D-iPhone 标准的 AddChild 添加给CCTMXTiledMap 的。