天天看點

cocos2d-x建立精靈動畫

建立動畫一般過程:

1、建立精靈架構緩存,并向其中添加相應的動畫檔案(plist),最後,通過動畫集緩存生産動畫

CCSpriteFrameCache *cache = CCSpriteFrameCache::sharedSpriteFrameCache();
    cache->addSpriteFramesWithFile("animations/grossini.plist");
    cache->addSpriteFramesWithFile("animations/grossini_gray.plist", "animations/grossini_gray.png");
    CCSpriteBatchNode *spritebatch = CCSpriteBatchNode::create("animations/grossini.png");//用于批量生産精靈 
    CCArray* animFrames = CCArray::createWithCapacity(15);//動态生成數組,類似于vector
    for(int i = 1; i < 4; i++)
    {
        //sprintf的作用是字元串格式化,主要功能是把格式化的資料寫入某個字元串中。sprintf(str, “ani_conch_%d.png”, 1)後str的值就變成了:ani_conch_1.png
        sprintf(str, "grossini_blue_%02d.png",i);//兩位數字,不夠的話,用零補全
        CCSpriteFrame *frame = cache->spriteFrameByName(str);
        animFrames->addObject(frame);
    }
    animation = CCAnimation::createWithSpriteFrames(animFrames, 0.2f);   //建立動畫集,切換時間為0.2s
    // Add an animation to the Cache
    CCAnimationCache::sharedAnimationCache()->addAnimation(animation, "dance_blue"); // 把此動畫集加入動畫集緩存中,并命名為dance_blue
    CCAnimationCache *animCache = CCAnimationCache::sharedAnimationCache();     //共享動畫集緩存 
    CCAnimation *normal = animCache->animationByName("dance");      //獲得動畫集緩存
    CCAnimate *animN = CCAnimate::create(normal);      //建立動畫
           

另外,CCString * str = CCString ::createWithFormat ( "market_chipsLogo%d.png" , idx);也可以實作替換數字的效果。

   2、直接傳人多個圖檔檔案,生成動畫

CCSprite *mainsprite=CCSprite::create("catBody1.png");
    CCAnimation *animation=CCAnimation::create();
    animation->addSpriteFrameWithFileName("catBody1.png");
    animation->addSpriteFrameWithFileName("catBody2-4.png");
    animation->addSpriteFrameWithFileName("catBody3.png");
    animation->addSpriteFrameWithFileName("catBody2-4.png");
    animation->setDelayPerUnit(0.1f);//設定動畫的間隔時間
    animation->setRestoreOriginalFrame(true);//是否傳回第一幀
    mainsprite->runAction(CCRepeatForever::create(CCAnimate::create(animation)));
           

3、直接傳入一張大圖,包含多個小圖,生成動畫

CCTexture2D *pTexture=CCTextureCache::sharedTextureCache()->addImage("hero.png");
    CCSpriteFrame *frame0=CCSpriteFrame::createWithTexture(pTexture,CCRectMake(0,0,32,32));
    CCSpriteFrame *frame1=CCSpriteFrame::createWithTexture(pTexture,CCRectMake(32,0,32,32));
    CCSpriteFrame *frame2=CCSpriteFrame::createWithTexture(pTexture,CCRectMake(64,0,32,32));
    CCSpriteFrame *frame3=CCSpriteFrame::createWithTexture(pTexture,CCRectMake(96,0,32,32));
    CCArray  *animFrames=CCArray::create();
    CC_BREAK_IF(!animFrames);
    animFrames->addObject(frame0);
    animFrames->addObject(frame1);
    animFrames->addObject(frame2);
    animFrames->addObject(frame3);
    CCAnimation *animation=CCAnimation::createWithSpriteFrames(animFrames,0.2f);
    heroSprite0->runAction(CCRepeatForever::create(animate));
           

   歡迎轉載,轉載請注明出處:http://blog.csdn.net/somestill/article/details/9852159