Cocos2dx 3.0 過渡篇(十三) action的用法從一個故事說起
本篇博客來自star特530,轉載請注明出處。https://blog.csdn.net/start530/article/details/20153367-------------
動作到底該怎麼玩?說的也就是runAction這貨了。
如果你覺得本文還是在寫像MoveTo,SacleTo這類動作的用法的話,那你就錯了。那樣不夠厚道。當然了,像Sequence,Spawn這類的東西多少也是會涉及到一點的。那到底要寫什麼呢?我們的故事從這裏開始。
首先我們創建倆精靈,就命名為boy 和 girl 吧。
- auto size = Director::getInstance()->getWinSize();
- auto boy = Sprite::create("boy.png");
- boy->setPosition(Point(0,size.height/2));//將boy的位置設置在最左邊
- this->addChild(boy,1);
- auto girl = Sprite::create("girl.png");
- girl->setPosition(Point(size.width,size.height/2));//將girl的位置設置在最右邊
- this->addChild(girl,1);
(故事的開始,boy 和 girl互相都不認識,直到有一天,倆人相遇了)
boy 和 girl 同時運動到場景中間
- boy->runAction(MoveTo::create(1.0f,Point(size.width/2-20,size.height/2)));//boy的速度明顯比girl的快。
- girl->runAction(MoveTo::create(1.5f,Point(size.width/2 +10,size.height/2)));
(boy看到girl的那一刻,驚呆了。他知道,她就是他一直在尋找的那個人。這,就是一見鍾情)
boy用原地旋轉360 + 全身血液膨脹來表達他的激動心情。表現方式有兩種:
- //1、邊旋轉邊全身膨脹
- boy->runAction(Spawn::create(RotateBy::create(1.0f,360),ScaleTo::create(1.0f,1.2f),NULL));
- //2、先旋轉完再全身膨脹
- boy->runAction(Sequence::create(RotateBy::create(1.0f,360),ScaleTo::create(1.0f,1.2f),NULL));
這裏表現的動作就是 girl要在boy旋轉+放大的動作做完後,才表現出她的...額,她的什麼來著?對了,女的比較活潑,應該跳起來。恩,於是girl跳了起來。
- //這裏的重點是girl應該怎樣才能在boy做完action後執行她的動作呢?有以下幾種辦法
- //1、用延遲的DelayTime來實現,也就是boy運動完後延遲幾秒,然後讓girl運動
- //延遲2.5s,用1s時間跳了3次,跳躍高度100像素,並且向右移動了30像素
- girl->runAction(Sequence::create(DelayTime::create(2.5f),JumpBy::create(1.0f,Point(30,0),100,3),NULL));
- //2、用回調函數實現,當boy完成後,寫一個lambda表達式來實現girl要做的動作(lambda表達式的使用可以參考我上一篇博客)
- boy->runAction(Sequence::create(RotateBy::create(1.0f,360),ScaleTo::create(1.0f,1.2f),
- CallFunc::create([=]()
- {
- //用1s時間跳了3次,跳躍高度100像素,並且向右移動了30像素
- girl->runAction(JumpBy::create(1.0f,Point(30,0),100,3));
- }),NULL));
- //3、用現成的接口TargetedAction();
- auto jump = JumpBy::create(1.0f,Point(30,0),100,3);//先寫一個跳躍的動作
- auto targetAct = TargetedAction::create(girl,jump);//寫一個目標動作,將動作執行人girl和要執行的動作jump放入其中
- //將girl的目標動作放入boy的sequence裏去
- boy->runAction(Sequence::create(RotateBy::create(1.0f,360),ScaleTo::create(1.0f,1.2f),targetAct,NULL));
有情人終成眷屬,故事的最後,允許我用一顆閃爍的心來表達對他們的祝福。希望他們能永遠在一起!!!
- //創建逐幀動畫
- auto spriteFrameCache = SpriteFrameCache::sharedSpriteFrameCache();
- spriteFrameCache->addSpriteFramesWithFile("heart.plist"); //將動畫圖片的plist放入緩存中
- SpriteFrame* frame = NULL;
- auto frameArray = Array::create();
- for(int i=0;i<10;i++)
- {
- frame = spriteFrameCache->spriteFrameByName(CCString::createWithFormat("%s%d.png","heart",i)->getCString());
- frameArray->addObject(frame);
- }
- auto animation = Animation::createWithSpriteFrames(frameArray,0.15f);
- auto animate = Animate::create(animation);//創建一個動畫
- auto heard_sp = Sprite::create("heart.png");
- heard_sp->setPosition(Point(size.width/2,size.height-200));
- heard_sp->runAction(animate);//播放動畫
- this->addChild(heard_sp,2);
故事簡單,過程卻沒那麼容易,結局也沒想象的那麼美好。
本篇博客來自star特530,轉載請注明出處。https://blog.csdn.net/start530/article/details/20153367
最後更新:2017-04-03 12:56:12