动画是游戏的必然要素之一,在整个游戏过程当中,又有着加速、减速动画的需求。以塔防为例子,布塔的时候但愿可以将游戏减速,布好塔后,则但愿能将游戏加速;当某个怪被冰冻后,移动速度减缓,而其余怪的移动速度不变。cocos2d-x引擎为咱们提供了很强大的接口函数
1)实现全局的加速、减速。动画
经过设置Scheduler的timeScale,能够实现全局的加、减速。代码很是简单:spa
CCScheduler* pScheduler = CCDirector::sharedDirector()->getScheduler(); pScheduler->setTimeScale(2.0f); //实现加速效果 pScheduler->setTimeScale(0.5f);//实现减速效果
2)实现对某个CCActionInterval动做的加速、减速code
方法一:很容易想到的一个方法就是改变CCAnimation的delay unit。代码以下:orm
AnimationCache* cache = CCAnimationCache::sharedAnimationCache(); CCAnimation* pAnimation = cache->animationByName(“xxx”); pAnimation->setDelayUnit(pAnimation->getDelayUnit()*0.2f); //速度为原来的5倍
这个方法有一个缺点:改变了CCAnimationCache中这个animation的delay unit。也就是说之后即便再从CCAnimationCache中获取这个animation,其delay unit已是原来的0.2倍了。对象
方法二:cocos2d-x提供了CCSpeed的类,能够实现动画速度的调节。用法以下:接口
CCActionInterval* act= CCMoveTo::create(5.0f, ccp(500.0f, 100.0f)); CCSpeed* pSpeed = CCSpeed::create(act, 1.5f); //1.5倍速运行 CCSpeed* pSpeed1 = CCSpeed::create(act, 0.2f);//0.2倍速运行 pSprite->runAction(pSpeed);
注意,若是pSprite有已经运行的动做,要用pSprite->stopActionByTag()停掉以前的动做,否则两个动做就叠加到一块儿了。游戏
3)对某个CCFiniteTimeAction类型动做的加速、减速get
大部分时候,一个游戏人物的动做并不是由单一一个CCActionInterval类型的动做构成,而是一串动做连起来,构成一个Sequence。 用CCSequence::create(…)建立的对象都是CCFinteTimeAction类型的,CCSpeed并不适用。在CCSpeed类的说明里,明确指 出”This action can’t be Sequenceable because it is not an CCIntervalAction”。 那对于Sequence就一筹莫展了吗?非也。cocos2d-x引擎自带例子中,schedulerTest给咱们展现了如何控制某个sprite的 scheduler的timescaleanimation
在class TwoSchedulers中定义了两个customer的scheduler和两个CCActionManager。
CCScheduler *sched1; CCScheduler *sched2; CCActionManager *actionManager1; CCActionManager *actionManager2;
//在onEnter函数中,分别对两个sprite设置customer的ActionManager.
CCScheduler *defaultScheduler = CCDirector::sharedDirector()->getScheduler(); // Create a new scheduler, and link it to the main scheduler sched1 = new CCScheduler(); defaultScheduler->scheduleUpdateForTarget(sched1, 0, false); // Create a new ActionManager, and link it to the new scheudler actionManager1 = new CCActionManager(); sched1->scheduleUpdateForTarget(actionManager1, 0, false); // Replace the default ActionManager with the new one. pSprite1->setActionManager(actionManager1);
经过以上的代码,就能够经过改变sched1的timescale来改变pSprite1的动做的快慢了。有了这种方法,那么就能够放弃CCSpeed的那种方法了。