我们这个Demo的效果就是点击屏幕实现武器的更换.人物换装应该是游戏中很常见的一个需求,故写此Demo以分享给需要的人.
一、我们直接在COCOS2D-X自带的HelloCpp的工程中添加代码即可.我们在初始化中添加如下代码:
[cpp] view plaincopy
1 CCSize szWin = CCDirector::sharedDirector()->getVisibleSize();
2 CCArmatureDataManager::sharedArmatureDataManager()->addArmatureFileInfo("knight.png","knight.plist","knight.xml");//加载骨骼动画文件
3 CCArmatureDataManager::sharedArmatureDataManager()->addArmatureFileInfo("weapon.png","weapon.plist","weapon.xml");//加载骨骼动画文件
4 setTouchEnabled(true);//开启触屏响应
5 pArmature = CCArmature::create("Knight_f/Knight");
6 pArmature->getAnimation()->playByIndex(0);//播放第一个动作
7 pArmature->setPosition(ccp(szWin.width/2-100,szWin.height/2));
8 pArmature->setScale(1.5f);
9 this->addChild(pArmature);
10 std::string sWeaponName[] = {"weapon_f-sword.png", "weapon_f-sword2.png", "weapon_f-sword3.png", "weapon_f-sword4.png", "weapon_f-sword5.png"};
11 CCSpriteDisplayData sprDisplayData;
12 for (int i=0;i<sizeof(sWeaponName)/sizeof(sWeaponName[0]);i++)
13 {
14 sprDisplayData.setParam(sWeaponName[i].c_str());
15 pArmature->getBone("weapon")->addDisplay(&sprDisplayData,i); //17
16 }
二、由于我们用到了COCOS2D-X中extensions中的类,故需要加入对应的目录和相应的头文件以及lib文件
①、在 工程->属性->配置属性->VC++目录->包含目录中添加extensions文件夹的路径:$(SolutionDir)\extensions
②、添加头文件、命名空间以及涉及的库文件如下:
[cpp] view plaincopy
17 #include "cocos-ext.h"
18 #include "CCArmature/utils/CCArmatureDataManager.h"
19 #include "CCArmature/CCArmature.h"
20 #pragma comment(lib,"libBox2d.lib")
21 #pragma comment(lib,"libExtensions.lib")
22 using namespace extension;
三、注册触屏分配器和设置其优先级
[cpp] view plaincopy
23 void TestUseMutiplePicture::registerWithTouchDispatcher()
24 {
25 CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this,0, true);
26 }
三、响应触屏事件以实现换装.代码如下:
[cpp] view plaincopy
27 bool HelloWorld::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
28 {
29 static int nDisplayIndex = -1;
30 ++nDisplayIndex;
31 nDisplayIndex = (nDisplayIndex)%5;
32 pArmature->getBone("weapon")->changeDisplayByIndex(nDisplayIndex,true); //17
33 return false;
34 }
四、程序运行效果截图.是不是觉得霸气外露