cocos2d-x學習之路(9)--重構項目(2)

項目已經分離出了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 once

template <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中通過動畫管理器創建動作

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章