本人初学cocos2dx,网上找了个例子,写一遍,自己领悟一翻,现在把自己的理解配上注释,
一步步深入理解这个小程序,希望可以帮助初始入门的朋友们。
首先建立一个Entity实体类,以便怪物类和玩家类可以继承:
#include "cocos2d.h"
/**
* @brief 精灵实体类
*
* 绑定精灵、获取精灵
*/
class Entity : public cocos2d::CCNode {
public:
/** @{
* @name 构造函数、析构函数、
*/
/// 构造函数
Entity();
/// 析构函数
virtual ~Entity();
/** @}
*/
/** @{
* @name getter、setter方法
*/
/**
* @brief 获取精灵
*/
cocos2d::CCSprite *getSprite();
/**
* @brief 绑定精灵
*/
void setSprite(cocos2d::CCSprite *pSprite);
/** @}
*/
private:
cocos2d::CCSprite *m_pSprite; ///< 精灵对象
};
#include "Entity.h"
USING_NS_CC;
Entity::Entity() : CCNode(), m_pSprite(NULL) {
return;
}
Entity::~Entity() {
// 使用自带的宏,方便安全
CC_SAFE_RELEASE_NULL(m_pSprite);
return;
}
CCSprite *Entity::getSprite() {
return m_pSprite;
}
void Entity::setSprite(cocos2d::CCSprite *pSprite) {
this->m_pSprite = pSprite;
CC_SAFE_RETAIN(this->m_pSprite); // 防止被释放
this->addChild(m_pSprite);
return;
}
接下来,先创建一个有特效效果的文本显示类:
/**
* @brief 文字飘动特效效果类
*/
class FlowTextLabel : public cocos2d::CCNode {
public:
/**
* 构造函数
*/
FlowTextLabel();
/**
* 析构函数
*/
virtual ~FlowTextLabel();
/**
* 初始化函数
*/
virtual bool init();
/**
* 创建FlowTextLabel对象,自动释放对象
*/
CREATE_FUNC(FlowTextLabel);
/**
* @brief 显示文本
* @param pText 文本
* @param pos 显示的位置
*/
void showText(const char *pText, cocos2d::CCPoint pos);
/**
* @brief 隐藏文本
*/
void hideText();
private:
cocos2d::CCLabelTTF *m_pText; ///< 文本文字
};
#include "FlowTextLabel.h"
USING_NS_CC;
FlowTextLabel::FlowTextLabel() : m_pText(NULL) {
CCNode::CCNode();
return;
}
FlowTextLabel::~FlowTextLabel() {
CC_SAFE_RELEASE_NULL(m_pText);
CCNode::~CCNode();
return;
}
bool FlowTextLabel::init() {
bool bRet = false;
do {
CC_BREAK_IF(!CCNode::init());
m_pText = CCLabelTTF::create("", "Arial", 30);
CC_BREAK_IF(!m_pText);
m_pText->setColor(ccc3(255, 0, 0));
m_pText->setVisible(false);
this->addChild(m_pText);
bRet = true;
} while (0);
return bRet;
}
void FlowTextLabel::showText(const char *pText, CCPoint pos) {
m_pText->setString(pText);
m_pText->setPosition(pos);
m_pText->setVisible(true);
m_pText->setAnchorPoint(ccp(1, 0));
// 先放大后缩小效果
CCScaleTo *pScaleLarge = CCScaleTo::create(0.3f, 2.5f, 2.5f);
CCScaleTo *pScaleSmall = CCScaleTo::create(0.4f, 0.5f, 0.5f);
// 动作回调
CCCallFunc *pCallFunc = CCCallFunc::create(this, callfunc_selector(FlowTextLabel::hideText));
CCActionInterval *pActions = CCSequence::create(pScaleLarge, pScaleSmall, pCallFunc, NULL);
this->runAction(pActions);
return;
}
void FlowTextLabel::hideText() {
m_pText->setVisible(false);
// 从父节点移除,并移除节点的动作和回调函数
m_pText->removeFromParentAndCleanup(true);
return;
}
接下来,创建一个继承于Entity的类,也就是玩家类:
#include "cocos2d.h"
#include "Entity.h"
/**
* @brief 玩家类
* 玩家动作:跳、受到攻击攻击伤害、吃掉金币
*/
class Player : public Entity {
public:
///
/// 构造函数、析构函数、初始化函数、创建玩家函数
Player();
virtual ~Player();
virtual bool init();
CREATE_FUNC(Player);
/**
* @brief 玩家跳起
*/
void jumpBegin();
/**
* @brief 玩家跳完毕
*/
void jumpEnd();
/**
* @brief 玩家与怪物碰撞(玩家受到攻击伤害)
*/
vo