Cocos2d-x初学指南(四): 生成animation 帧动画的2种方法

Cocos2d-x初学指南(4): 生成animation 帧动画的2种方法

方法一是用多套名字按一定规律的不同的单图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);

这个代码是网上随便百度的。http://blog.****.net/yanghuiliu/article/details/6933421

还有一种方法是多个图在一张合图上,这种更节约磁盘空间,我感觉哈。

 

//组合图
		CCTexture2D *birdTexture=CCTextureCache::sharedTextureCache()->addImage("bird2.png");
		CCMutableArray<CCSpriteFrame*>* myArray=new CCMutableArray<CCSpriteFrame*>(3);
		CCSpriteFrame *myframe1=CCSpriteFrame::frameWithTexture(birdTexture,CCRect(1,379,31,30));
		CCSpriteFrame *myframe2=CCSpriteFrame::frameWithTexture(birdTexture,CCRect(1,411,31,30));
		CCSpriteFrame *myframe3=CCSpriteFrame::frameWithTexture(birdTexture,CCRect(1,508,30,28));
		CCSpriteFrame *myframe4=CCSpriteFrame::frameWithTexture(birdTexture,CCRect(1,538,30,29));
		myArray->addObject(myframe1);
		myArray->addObject(myframe2);
		myArray->addObject(myframe3);
		myArray->addObject(myframe4);
		CCAnimation *animation=CCAnimation::animationWithFrames(myArray,1.0f);
		CCRepeatForever *myaction=CCRepeatForever::actionWithAction(CCAnimate::actionWithAnimation(animation,false));
		CCSprite *mybird=CCSprite::spriteWithSpriteFrame(myframe1);
		this->addChild(mybird);
		mybird->setPosition(ccp(200,300));
		mybird->runAction(myaction);
		myArray->release();