参考资料:http://4137613.blog.51cto.com/4127613/759610
资源图片:
代码:
bool HelloWorld::init()
{
bool bRet = false;
do
{
// 获得屏幕大小
CCSize size = CCDirector::sharedDirector()->getWinSize();
// 读取纹理
CCTexture2D* pTexture = CCTextureCache::sharedTextureCache()->addImage("anim1.png");
//1:生成动画需要的数据类
CCSpriteFrame* frame0 = CCSpriteFrame::createWithTexture( pTexture, CCRectMake( 32*0, 48*0, 32, 48 ) );
CCSpriteFrame* frame1 = CCSpriteFrame::createWithTexture( pTexture, CCRectMake( 32*1, 48*0, 32, 48 ) );
CCSpriteFrame* frame2 = CCSpriteFrame::createWithTexture( pTexture, CCRectMake( 32*2, 48*0, 32, 48 ) );
CCSpriteFrame* frame3 = CCSpriteFrame::createWithTexture( pTexture, CCRectMake( 32*3, 48*0, 32, 48 ) );
CCAnimation *animation = CCAnimation::create();
animation->addSpriteFrame(frame0);
animation->addSpriteFrame(frame1);
animation->addSpriteFrame(frame2);
animation->addSpriteFrame(frame3);
animation->setDelayPerUnit(0.2f);
CC_BREAK_IF( !animation );
//2:初始化并设置Sprite
CCSprite *sprite = CCSprite::createWithSpriteFrame(frame0);//设置一个初始frame
CC_BREAK_IF( !sprite );
sprite->setPosition( ccp( 200, 200) );
this->addChild( sprite, 2 );
//3:使用animation生成一个动画动作animate
CCAnimate *animate = CCAnimate::create(animation);
CC_BREAK_IF( !animate );
CCRepeatForever *repeat = CCRepeatForever::create(animate);
sprite->runAction(repeat);//重复播放
bRet = true;
} while (0);
return bRet;
}