从图书馆借了本木头的书籍,以下实例来自书籍,写在这里仅作笔记。。
游戏内容大概如下:
1.一个Sprite在地图上一直在跑,Sprite可以跳跃(其实是地图不断向左滚动)
2.途中有金币,Sprite吃金币,左上方的Score会++,并且会有+15的字样出现
1.创建实体类Entity,这是一个基类,主要用来绑定一个精灵,返回一个精灵
#ifndef Entity_H
#define Entity_H
#include "cocos2d.h"
using namespace cocos2d;
class Entity:public CCNode
{
public:
Entity();
~Entity();
CCSprite* getSprite();
void bindSprite(CCSprite* sprite);
private:
CCSprite* m_sprite;
};
#endif
#include "Entity.h"
Entity::Entity()
{
m_sprite=NULL;
}
Entity::~Entity()
{
};
CCSprite* Entity::getSprite()
{
return this->m_sprite;
}
void Entity::bindSprite(CCSprite* sprite){
this->m_sprite=sprite;
this->addChild(m_sprite);
}
2.创建一个玩家主角类,可以jump,吃金币等
#ifndef _Player_H
#define _Player_H
#include "cocos2d.h"
#include "Entity.h"
using namespace cocos2d;
#define JUMP_ACTION_TAG 1;
class Player:public Entity
{
public:
Player();
~Player();
CREATE_FUNC(Player);
virtual bool init();
public:
void jump();
void jumpEnd();
void hit();//主角和怪物撞击(玩家受伤害)
int getMoney();
CCRect getBoundingBox();/*获取碰撞范围*/
void resetData();
void actionEnd();
private:
bool m_isJumping;
int m_money;/*金钱*/
};
#endif#include "Player.h"
#include "FlowWord.h"
Player::Player()
{
m_isJumping=false;
m_money=0;/*初始金钱为0*/
}
Player::~Player()
{
}
bool Player::init()
{
return true;
}
void Player::jump()
{
if(!getSprite())
{
return;
}
if(m_isJumping)/*如果主角还在跳跃中,则不重复跳跃*/
{
return;
}
m_isJumping=true;
/*创建动作,2s,原地跳跃(即落地的地点相对于起跳地点x偏移0,y偏移0),高度250,弹跳次数1*/
CCJumpBy* jump=CCJumpBy::create(1.5f,ccp(0,0),200,1);
/*callFunc也是一个动作,作用是调用一个函数*/
CCCallFunc* callFunc = CCCallFunc::create(this, callfunc_selector(Player::jumpEnd));
/*组合动作*/
CCActionInterval* jumpActions=CCSequence::create(jump,callFunc,NULL);
runAction(jumpActions);
}
void Player::jumpEnd()
{
m_isJumping=false;
}
void Player::hit()
{
if(getSprite()==NULL)
{
return;
}
/*加钱特效提示*/
FlowWord* flowword=FlowWord::create();
this->addChild(flowword);
flowword->showWord("+15",getSprite()->getPosition());
m_money+=15;
/*创建4种动作对象*/
CCMoveBy* backMove=CCMoveBy::create(0.1f,ccp(-20,0));
CCMoveBy* forwardMove=CCMoveBy::create(0.1f,ccp(20,0));
CCRotateBy* backRotate=CCRotateBy::create(0.1f,-5,0);
CCRotateBy* forwardRotate=CCRotateBy::create(0.1f,5,0);
/*分别组合成两种动作(同时执行)*/
CCSpawn* backActions=CCSp