cocos2d-x基础<三> 播放动画

1. 加载一张纹理,创建CCTexture2D,并在这张纹理上划分出多个CCSpriteFrame:
    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);


4. 最后,要在屏幕上显示出动画,需要创建一个CCSprite实例,然后让它循环播放上面的CCAnimate动作。注意,必须用CCRepeatForever::actionWithAction来包装animate,否则动画只播放一次就停下了。

    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) );





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值