1. 程式人生 > >cocos2d-x幀動畫實現(續)

cocos2d-x幀動畫實現(續)

猴子原創, 歡迎轉載,轉載請在明顯處註明! 謝謝。

幀動畫就是很多張png的序列圖實現輪流播放產生動畫效果。

那麼首先我們要一套動畫的序列圖,沒有圖的可以看引擎例子裡面的圖。很多張圖我們可以採用TP工具將它們壓縮到一張png裡面去,這樣程式只需要讀取一次就行了,提高效率。


比如我將這裡的6張圖壓成了一個png,TP會產生一個所有圖的png和一個plist描述檔案,plist很像xml,它描述了每一張圖的位置,大小等資訊。程式就是通過plist檔案在合成的大png裡面找到每一張圖的。

合成的大圖叫fei.png,對應的fei.plist。

裡面的小圖。叫 飛0001.png、飛0002.png、.........飛0006.png

下面開始程式的建立

            //建立cache
    CCSpriteFrameCache* cache = CCSpriteFrameCache::sharedSpriteFrameCache();
    char strPlist[64] = {0};
    char strPng[64] = {0};
    sprintf(strPlist,"fei.plist");
    //sprintf(strPng,"fei.pvr.ccz"); 
    sprintf(strPng,"fei.png");
    cache->addSpriteFramesWithFile(strPlist, strPng);
    
    //建立動畫每一幀,從cache裡面讀取
    CCMutableArray<CCSpriteFrame*>* animFrames = new CCMutableArray<CCSpriteFrame*>(6);
    
    char str[64] = {0};
    for(int i = 1; i <= 6; i++) 
    {
        sprintf(str, "飛%04d.png", i);
        CCSpriteFrame* frame = cache->spriteFrameByName( str );
        animFrames->addObject(frame);
    }
    
    CCAnimation* animation = CCAnimation::animationWithFrames(animFrames,0.04f);
   
    CCRepeatForever* mFly=CCRepeatForever::actionWithAction( CCAnimate::actionWithAnimation(animation, false));
    animFrames->release();
    cache->removeSpriteFramesFromFile(strPlist);

這裡的mFly就是一個建立好的action。當然它是可以重複播放的。你要是隻想播放一次。

那麼替換成

CCActionInterval* mFly=CCAnimate::actionWithAnimation(animation,true);

你可能看到了我裡面註釋了一行程式碼,就是我不是壓縮成了png,而是壓縮成了pvr.ccz。這種格式效率更高。

pvr是蘋果自己支援的圖片格式,但是比較佔記憶體,壓縮成ccz後就很小了。用法一樣。