学习这个之前,你首先要对cocos2d-x动作类有一个基础的认识。不知道的童鞋就先去学习一下相关知识吧.
好了,如果你了解过cocos2d-x动作类的话,接下来就可以跟着我完成一个人物行走的的实现。
首先人物行走肯定是从一个地方移动到一个地方 那我们就要用到CCMoveBy类来实现人物的移动,
其次,人物在行走的时候是有动作的,脚的摆动,手的摆动等。这样我们就需要创建一个动画。
根据这两点,我们来实现人物行走:
(1)人物移动:
CCPoint moveByPosition;
switch(moveDirection) //根据moveDirection的值来选择上下左右
{
case up:
moveByPosition = ccp(0,10);
break;
case down:
moveByPosition = ccp(0,-10);
break;
case left:
moveByPosition = ccp(-10,0);
break;
case right:
moveByPosition = ccp(10,0);
break;
default:
moveByPosition = ccp(0,0);
break;
}
CCMoveBy *moveBy = CCMoveBy::create(0.3f,moveByPosition);//创建移动动作
(2)行走动画:
创建动画可以用纹理图片来创建,也可以用单独的图片来创建。
纹理图片创建:
//将图片生成纹理,保存到全局的纹理缓存取
CCTexture2D *heroTexture=CCTextureCache::sharedTextureCache()->addImage("hero.png");
//用纹理创建4幅帧动画,第二个参数表示纹理图片区域的x,y,width,height,根据direction的不同分别为向上、下、左、右移动的动画
CCSpriteFrame *frame0,*frame1,*frame2,*frame3;
frame0=CCSpriteFrame::createWithTexture(heroTexture,cocos2d::CCRectMake(Rect*0,Rect*direction,Rect,Rect));
frame1=CCSpriteFrame::createWithTexture(heroTexture,cocos2d::CCRectMake(Rect*1,Rect*direction,Rect,Rect));
frame2=CCSpriteFrame::createWithTexture(heroTexture,cocos2d::CCRectMake(Rect*2,Rect*direction,Rect,Rect));
frame3=CCSpriteFrame::createWithTexture(heroTexture,cocos2d::CCRectMake(Rect*3,Rect*direction,Rect,Rect));
CCArray *animFrames=CCArray::create();
animFrames->addObject(frame0);
animFrames->addObject(frame1);
animFrames->addObject(frame2);
animFrames->addObject(frame3);
//根据4幅帧生成CCAnimation对象
CCAnimation *animation=CCAnimation::createWithSpriteFrames(animFrames);
根据单张图片来创建动画:
/*****************************************************************************
CCAnimation *animation = CCAnimation::create();
//根据direction的不同分别为向上、下、左、右移动的动画
string Image1 = direction+"player1.png";
string Image2 = direction+"player1.png";
string Image3 = direction+"player1.png";
string Image4 = direction+"player1.png";
animation->addSpriteFrameWithFileName(Image1.c_str());
animation->addSpriteFrameWithFileName(Image2.c_str());
animation->addSpriteFrameWithFileName(Image3.c_str());
animation->addSpriteFrameWithFileName(Image4.c_str());
//设置动画播放的属性,每一帧的时间0.3f
animation->setDelayPerUnit(0.3f);
animation->setRestoreOriginalFrame(true);
***********************************************************************************/
根据移动和行走动画来创建动画动作:
CCAction *action = CCSequence::create(
CCSpawn::create( //两个动作同步进行
CCAnimate::create(animation),
moveBy,
NULL
),
// function //CCCallFuncN,CCCallFunc,CCCallFuncND创建函数调用
NULL
);
//最后,让hero精灵执行这个动作
hero->runAction(action);
这样人物行走的动作功能就实现了。如果开发者还想在精灵完成动作后执行某些功能,可以用
CCCallFuncN,CCCallFunc,CCCallFuncND创建函数调用放在最后。这样等精力完成动作后就会
自动调用创建的函数实现某些功能了