cocos2d-x基础三 播放动画
1. 加载一张纹理,创建CCTexture2D,并在这张纹理上划分出多个CCSpriteFrame:
3. 但是cocos2d的CCAnimation不是一个可以用来显示的类型,它只负责记录动画帧、帧间隔等数据,要让它动起来,需要借助CCAnimate,它是一种Action。
CCTexture2D *texture = CCTextureCache::sharedTextureCache()->addImage("animations/dragon_animation.png");
// manually add frames to the frame cache
CCSpriteFrame *frame0 = CCSpriteFrame::frameWithTexture(texture, CCRectMake(132*0, 132*0, 132, 132));
CCSpriteFrame *frame1 = CCSpriteFrame::frameWithTexture(texture, CCRectMake(132*1, 132*0, 132, 132));
CCSpriteFrame *frame2 = CCSpriteFrame::frameWithTexture(texture, CCRectMake(132*2, 132*0, 132, 132));
CCSpriteFrame *frame3 = CCSpriteFrame::frameWithTexture(texture, CCRectMake(132*3, 132*0, 132, 132));
CCSpriteFrame *frame4 = CCSpriteFrame::frameWithTexture(texture, CCRectMake(132*0, 132*1, 132, 132));
CCSpriteFrame *frame5 = CCSpriteFrame::frameWithTexture(texture, CCRectMake(132*1, 132*1, 132, 132));
2. 通过上面的CCSpriteFrame创建出一个CCAnimation。
CCMutableArray<CCSpriteFrame*> *animFrames = new CCMutableArray<CCSpriteFrame*>(6);
animFrames->addObject(frame0);
animFrames->addObject(frame1);
animFrames->addObject(frame2);
animFrames->addObject(frame3);
animFrames->addObject(frame4);
animFrames->addObject(frame5);
CCAnimation *animation = CCAnimation::animationWithFrames(animFrames, 0.2f);
3. 但是cocos2d的CCAnimation不是一个可以用来显示的类型,它只负责记录动画帧、帧间隔等数据,要让它动起来,需要借助CCAnimate,它是一种Action。
CCAnimate *animate = CCAnimate::actionWithAnimation(animation, false);
CCSprite* sprite = CCSprite::spriteWithSpriteFrame(frame0);
sprite->setPosition( ccp( s.width/2-80, s.height/2) );
layer->addChild(sprite);//把sprite添加到CCLayer上,才能显示
sprite->runAction(CCRepeatForever::actionWithAction( animate) );