cocos2d-x学习之路(9)--重构项目(2)

来源:互联网 发布:linux ftp修改访问目录 编辑:程序博客网 时间:2024/06/07 23:12

项目已经分离出了GameScnene,GameLayer和GameMap类,接下来分离出一个Hero类

因为Hero类今后为保存Hero的很多其他属性,例如血条、光环,也就是说需要在Hero中添加子节点,所以Hero不继承CCSprite,而是继承CCNoe,Hero精灵作为成员变量。

再将其他的相关属性添加到Hero类中,在heroMove()方法中,原先由精灵通过CCSpawn同时控制动作和移动,而今后可能需要多个精灵同时移动,所以hersprite只负责动画播放,hero负责控制移动

hero.h

typedef enum {keyDown=0,keyLeft=1,keyRight=2,keyUp=3}HeroDirection;class Hero : public CCNode{public:Hero();~Hero();static Hero * heroWithinLayer();bool heroInit();void heroMove(HeroDirection direction);void onWalkDone(CCNode *pTarget, void* data);public:ColorSprite * m_heroSprite;bool  m_isHeroMove;HeroDirection  m_curDirection;};


 

void Hero::heroMove(HeroDirection direction){if (m_isHeroMove){return;
}//动画创建函数的调用以后会作修改
CCAnimate * animate=CCAnimate::create(createHeroAnimation(direction));CCPoint moveByPosition;//根据方向计算移动的距离
          /*·········*/
m_heroSprite->runAction(animate);CCPoint targetPosition=ccpAdd(this->getPosition(),moveByPosition);CCMoveBy *moveBy=CCMoveBy::create(0.20f,moveByPosition);CCSpawn * spawn=CCSpawn::create(animate,moveBy,NULL);CCAction *action=CCSequence::create(moveBy,CCCallFuncND::create(this, callfuncND_selector(Hero::onWalkDone), (void*)direction),NULL);//并让hero控制移动
this->runAction(action);m_isHeroMove=true;
}


游戏中动画的创建管理并不需要一个具体的对象,而且在项目中有许多地方都需要用到动画创建,所以使用单例创建游戏动画管理器

先创建一个单例模板(注意:模板类的函数定义也需要放在.h中 ,否则会报错)

#pragma oncetemplate <class T>class Singleton{public:static inline T* getInstance();void release();protected:Singleton();~Singleton()();static T * m_instance;};

然后创建一个类AnimationManager继承Singleton,它拥有一个动画映射表,通过key值获取相应动画

#include "header.h"#include "Singleton.h"#include "Hero.h"using namespace cocos2d;typedef enum{aDown=0,aLeft=1,aRight=2,aUp=3}AnimationKey;class AnimationManager : public Singleton<AnimationManager>{public:AnimationManager();~AnimationManager();//初始化动画模板bool initAnimationMap();//返回动画模版CCAnimation * getAnimation(int key);//返回动画实例CCAnimate* createAnimate(int key);protected:CCAnimation *createHeroAnimation(HeroDirection direction);};//定义别名#define AnimaManagerInstance AnimationManager::getInstance()


 

bool AnimationManager::initAnimationMap(){//将勇士的行走动画加载到全局动画池中char temp[20];sprintf(temp,"%d",aDown);CCAnimationCache::sharedAnimationCache()->addAnimation(createHeroAnimation(keyDown),temp);sprintf(temp,"%d",aLeft);CCAnimationCache::sharedAnimationCache()->addAnimation(createHeroAnimation(keyLeft),temp);sprintf(temp,"%d",aRight);CCAnimationCache::sharedAnimationCache()->addAnimation(createHeroAnimation(keyRight),temp);sprintf(temp,"%d",aUp);CCAnimationCache::sharedAnimationCache()->addAnimation(createHeroAnimation(keyUp),temp);return true;}

 


在  AppDelegate::applicationDidFinishLaunching() 中初始化动画管理器

AnimaManagerInstance->initAnimationMap();

然后就可以在 heroMove中通过动画管理器创建动作

原创粉丝点击