1.先定义坦克的一些属性
class Tank : public CCSprite { public : Tank(); ~Tank(); static Tank* createTankWithTankType(const char* tankTypeName); };上面定义很简单,我们暂时只用写一个函数createTankWithTankType,
2.函数功能就是从坦克类型创建坦克精灵,下面看实现:
Tank* Tank::createTankWithTankType(const char* tankTypeName) { CCSpriteFrameCache* pCache = CCSpriteFrameCache::sharedSpriteFrameCache(); pCache->addSpriteFramesWithFile("tank.plist"); Tank* tank = new Tank(); tank->initWithSpriteFrameName(tankTypeName); tank->autorelease(); return tank; }
plist文件我们使用 TexturePacker 打开:如图所示:
资源文件中有plist文件,可以加载进来查看
3.现在CityScene场景中添加成员变量Tank* mPlayerTank[2];,
然后在CityScene场景中加入我们的坦克精灵:
bool CityScene::init() { CCLayer::init(); CCTMXTiledMap* tmxFile = CCTMXTiledMap::create("Round1.tmx"); //将地图放到屏幕中间 CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCSize size = tmxFile->getContentSize(); tmxFile->setPosition(ccp((winSize.width - size.width)/2, (winSize.height - size.height)/2)); this->addChild(tmxFile); //将坦克缩放到合适大小,然后放到地图中合适位置 CCSize tileSize = tmxFile->getTileSize(); playerTank[0] = Tank::createTankWithTankType("player2U.png"); CCSize tankSize = playerTank[0]->getContentSize(); playerTank[0]->setScaleX(tileSize.width * 2 / tankSize.width); playerTank[0]->setScaleY(tileSize.height * 2 / tankSize.height); playerTank[0]->setPosition(ccp(winSize.width / 2 - tileSize.width * 2, tileSize.height)); this->addChild(playerTank[0], 2); return true; }
效果如下图所示:
TexturePacker 下载地址:
http://www.codeandweb.com/texturepacker/download
本篇文章源码下载地址:
http://download.csdn.net/detail/yincheng01/6749059