Cocos2d-x3.3beta0創建動畫的3種方式
阿新 • • 發佈:2017-06-28
sprintf action frame idt adding instance 修改 name 工具
1、單獨載入精靈對象
渲染效率低,浪費資源,不推薦用該方法。代碼例如以下:註:代碼僅僅需貼到HelloWorldScene.cpp中就可以。
//First,單獨渲染每個精靈幀 auto sprite = Sprite::create("grossini_dance_01.png"); sprite->setPosition(Vec2(visibleSize.width/2,visibleSize.height/4*3)); addChild(sprite); auto animation = Animation::create(); char strName[50] = {0}; for(int i = 1; i <= 14; i++) { sprintf(strName, "grossini_dance_%02d.png",i); animation->addSpriteFrameWithFile(strName);//將全部的精靈載入到animation } animation->setDelayPerUnit(3.0f / 14);//3秒內播放14幀動畫 animation->setRestoreOriginalFrame(true);//重頭開始播放 sprite->runAction(RepeatForever::create(Animate::create(animation)));//運行動作
2、一次載入,使用精靈幀
效率和資源有提高,可是使用Rect截取精靈對象不方便。代碼例如以下:
//Second,一次渲染 auto textTure = Director::getInstance()->getTextureCache()->addImage("dragon_animation.png"); SpriteFrame* frame0 = SpriteFrame::createWithTexture(textTure, Rect(132*0,132*0,132,200));//截取精靈幀 SpriteFrame* frame1 = SpriteFrame::createWithTexture(textTure, Rect(132*1,132*0,132,200)); SpriteFrame* frame2 = SpriteFrame::createWithTexture(textTure, Rect(132*2,132*0,132,200)); SpriteFrame* frame3 = SpriteFrame::createWithTexture(textTure, Rect(132*3,132*0,132,200)); SpriteFrame* frame4 = SpriteFrame::createWithTexture(textTure, Rect(132*0,132*1,132,200)); SpriteFrame* frame5 = SpriteFrame::createWithTexture(textTure, Rect(132*1,132*1,132,200)); Vector<SpriteFrame*> arr;//載入精靈幀 arr.pushBack(frame0); arr.pushBack(frame1); arr.pushBack(frame2); arr.pushBack(frame3); arr.pushBack(frame4); arr.pushBack(frame5); auto sp = Sprite::createWithSpriteFrame(frame0);//用第一幀精靈對象。初始化精靈 sp->setPosition(Vec2(visibleSize.width/2,visibleSize.height/2)); addChild(sp); auto animation1 = Animation::createWithSpriteFrames(arr,0.2f);//運行動作 sp->runAction(RepeatForever::create(Animate::create(animation1)));
3、使用TexturePacker打包精靈對象。幀載入
推薦使用該方法:1)打開TexturePacker工具。addSprite導入精靈對象。2)Data Format選擇cocos2d。3)Texture format使用PNG格式。Layout的Max Size W和H能夠修改。可是尺寸是2的冪。4)Publish sprite sheet,打包。保存地址就是project的Resource就可以。代碼例如以下:
//Third,first和second的集合,使用TexturePacker工具,將精靈對象打包 auto cache = SpriteFrameCache::getInstance(); cache->addSpriteFramesWithFile("animation.plist");//載入plist文件 auto sp1 = Sprite::createWithSpriteFrameName("grossini_dance_01.png");//使用第一幀精靈初始化對象,精靈對象的名字與plist中的名字一致 sp1->setPosition(Vec2(visibleSize.width/2,visibleSize.height/4)); addChild(sp1); Vector<SpriteFrame*> arr1; char str[50] = {0}; for(int i = 1; i <= 14; i++) { sprintf(str, "grossini_dance_%02d.png",i);//將精靈幀載入 auto frame = cache->getSpriteFrameByName(str); arr1.pushBack(frame); } //運行動作 auto animation2 = Animation::createWithSpriteFrames(arr1,0.1f); sp1->runAction(RepeatForever::create(Animate::create(animation2)));
4、效果圖
Cocos2d-x3.3beta0創建動畫的3種方式