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));
时间: 2024-10-17 13:58:09