cocos2d-x 2.0下生成动画

最近项目由coco2d-iphone直接签到cocos2d-x 2.0下,感觉coco2d-iphone与cocos2d-x还是有些区别的,之后一段时间都会贴一些cocos2d-x 2.0有关的东西,顺便说一下cocos2d-x 1.0和2.0也是有一定区别的,各位认准了使用吧!下面来看一段生成动画的代码:

//生成动画函数,参数是图片名前缀和动画持续时间
CCAnimation *HelloWorld::GetAnimate(const char *picname,float delay)
{
    //This is key point
    //char keyname[100]={0};
    char keyname[100];//函数返回后自动释放
    
    //sprintf(keyname,"%s.plist",filename);
    //CCSpriteFrameCache *cache=CCSpriteFrameCache::sharedSpriteFrameCache();  
    //cache->addSpriteFramesWithFile(keyname);  
    
    CCArray* animFrames = CCArray::create();
    //下标从1开始
    int i = 1;
    do {  
        sprintf(keyname,"%s_%d.png",picname,i);//命名格式为xxx.1.png
        //sprintf(keyname,"%s_%03d.png",picname,i);//命名格式为xxx.001.png
        //CCLog(keyname);
        CCSpriteFrame *frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(keyname);
        if (frame) {  
            animFrames->addObject(frame);  
        }else {  //如果获取不到帧就证明动画帧结束了
            break;  
        }  
    } while (++i);
    
    CCAnimation *animation = CCAnimation::createWithSpriteFrames(animFrames,delay);    
	return animation;
}

使用:

    CCSize size = CCDirector::sharedDirector()->getWinSize();
    
    //加载纹理
    CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("Spray.plist");  
    
    CCSprite *sprite=CCSprite::create("Spray_1.png");
    //通过纹理创建精灵
    sprite -> setPosition(ccp(size.width/2,size.height*0.80));
    this -> addChild(sprite,55,11);
    
    //通过纹理创建动画
    CCAnimation *animation=HelloWorld::GetAnimate("Spray",0.2f);
    
    //执行动作
    CCRepeatForever *repeat=CCRepeatForever::create(CCAnimate::create(animation));
    sprite->runAction(repeat);

是不是很简单呢!

你可能感兴趣的:(cocos2d-x,2.0)