cocos2dx 动画第一个demo

今晚写代码很带劲,所以又测试了一下cocos2dx的动画,基本是按照书上的思路写的,废话少说,直接贴代码:

帧动画如图:

cocos2dx 动画第一个demo_第1张图片

bool StartScene::initAnimation2()

{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();

        // 加载整个动画关键帧的纹理

CCTexture2D* pAnimationTexture = CCTextureCache::sharedTextureCache()->addImage("startscene_npc_0.png");
float wPerFrame = pAnimationTexture->getContentSize().width / 4;
float hPerFrame = pAnimationTexture->getContentSize().height / 4;

       // 设置每帧动画时间
CCAnimation* pNPCAnimation = CCAnimation::create();
pNPCAnimation->setDelayPerUnit(0.2f);


float moveDistance = 15.0f;


        // 动画其实也需要挂在一个精灵上,所以创建一个第一帧的精灵

CCSpriteFrame* frameStart = CCSpriteFrame::createWithTexture(pAnimationTexture, CCRectMake(0, 0, wPerFrame, hPerFrame));
CCSprite* pNPC = CCSprite::createWithSpriteFrame(frameStart);
pNPC->setPosition( ccp( winSize.width/2-moveDistance, 430) );

        

       // 加载其余帧,只加载上面两排横向走的动画

for (int i=0; i<2; i++)
{
for (int j=0; j<4; j++)
{
pNPCAnimation->addSpriteFrameWithTexture(pAnimationTexture, 
CCRectMake(j*wPerFrame, i*hPerFrame, wPerFrame, hPerFrame));
}
}
CCAnimate* pAnimate = CCAnimate::create(pNPCAnimation);
pNPC->runAction(CCRepeatForever::create(pAnimate));

        

        // 这个动画是一个NPC往右走四帧然后往左走四帧,所以与此同时加上两个位移的动作,就可以看上去NPC在走动了,

       // 时间设置 0.8f = 0.2f * 4;  0.2是每帧间隔时间,往一边走的动画有4帧。

CCMoveTo* pMoveRight = CCMoveTo::create(0.8f, ccp( winSize.width/2 + moveDistance, 430));
CCMoveTo* pMoveLeft = CCMoveTo::create(0.8f, ccp( winSize.width/2 - moveDistance, 430));


CCSequence* pMoveSeq=CCSequence::create(pMoveRight,pMoveLeft,NULL);  
CCRepeatForever* pMoveForever = CCRepeatForever::create((CCActionInterval*)pMoveSeq);
pNPC->runAction(pMoveForever);


addChild(pNPC);


return true;
}

你可能感兴趣的:(cocos2dx 动画第一个demo)