Cocos2d-x虚拟摇杆控制精灵上下左右运动----之游戏开发《赵云要(4)
来源:未知 责任编辑:责任编辑 发表时间:2015-09-09 15:29 点击:次
Hero.h
#ifndef __HERO_H__
#define __HERO_H__
#include "cocos2d.h"
#include "cocos-ext.h"
using namespace cocos2d;
USING_NS_CC_EXT;
class Hero:public cocos2d::CCNode
{
public:
Hero(void);
~Hero(void);
//根据图片名创建英雄
void InitHeroSprite(char *hero_name);
//设置动画,num为图片数目,run_directon为精灵脸朝向,false朝右,name_each为name_png中每一小张图片的公共名称部分
void SetAnimation(const char *name_plist,const char *name_png,const char *name_each,const unsigned int num,bool run_directon);
//停止动画
void StopAnimation();
//判断是否在跑动画
bool IsRunning;
//英雄运动的方向
bool HeroDirecton;
CREATE_FUNC(Hero);
private:
CCSprite* m_HeroSprite;//精灵
char *Hero_name;//用来保存初始状态的精灵图片名称
};
#endif // __HERO_H__
然后是Hero.cpp
#include "Hero.h"
USING_NS_CC;
USING_NS_CC_EXT;
Hero::Hero(void)
{
IsRunning=false;//没在放动画
HeroDirecton=false;//向右运动
Hero_name=NULL;
}
Hero::~Hero(void)
{
}
void Hero::InitHeroSprite(char *hero_name)
{
Hero_name=hero_name;
this->m_HeroSprite=CCSprite::create(hero_name);
this->addChild(m_HeroSprite);
}
//动画播放,可以是跑、攻击、死亡、受伤等
void Hero::SetAnimation(const char *name_plist,const char *name_png,const char *name_each,unsigned int num,bool run_directon)
{
if(HeroDirecton!=run_directon)
{ HeroDirecton=run_directon;
m_HeroSprite->setFlipX(run_directon);
}
if(IsRunning)
return;
//将图片加载到精灵帧缓存池
CCSpriteFrameCache *m_frameCache=CCSpriteFrameCache::sharedSpriteFrameCache();
m_frameCache->addSpriteFramesWithFile(name_plist,name_png);
//用一个列表保存所有的CCSpriteFrameCache
CCArray* frameArray= CCArray::createWithCapacity(num);
unsigned int i;
for(i=2;i<=num;i++)
{
CCSpriteFrame* frame=m_frameCache->spriteFrameByName(CCString::createWithFormat("%s%d.png",name_each,i)->getCString());
frameArray->addObject(frame);
}
//使用列表创建动画对象
CCAnimation* animation=CCAnimation::createWithSpriteFrames(frameArray);
if(HeroDirecton!=run_directon)
{ HeroDirecton=run_directon;
}
animation->setLoops(-1);//表示无限循环播放
animation->setDelayPerUnit(0.1f);//每两张图片的时间隔,图片数目越少,间隔最小就越小
//将动画包装成一个动作
CCAnimate* act=CCAnimate::create(animation);
m_HeroSprite->runAction(act);
IsRunning=true;
}
void Hero::StopAnimation()
{
if(!IsRunning)
return;
m_HeroSprite->stopAllActions();//当前精灵停止所有动画
//恢复精灵原来的初始化贴图
this->removeChild(m_HeroSprite,TRUE);//把原来的精灵删除掉
m_HeroSprite=CCSprite::create(Hero_name);//恢复精灵原来的贴图样子
m_HeroSprite->setFlipX(HeroDirecton);
this->addChild(m_HeroSprite);
IsRunning=false;
IsRunning=false;
}之后就在HelloWorldScene.h添加头文件#include "Hero.h",并加入成员变量
private:
Hero* hero;
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 进入详细评论页>>

![cocos2d_x+lua[2]](/uploads/allimg/131030/110J64609-0-lp.jpg)








