Cocos2dx Action动画机制

前端之家收集整理的这篇文章主要介绍了Cocos2dx Action动画机制前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1 动画执行过程

cocos中的动画通过节点执行,如:
node:runAction( cc.Sequence:create(cc.DelayTime:create(1.4),cc.CallFunc:create(removeThis)))
runAction方法将动画添加至动画管理器中。动画管理器将节点的动画信息全部关联至element中,并以节点作为key,element作为value生成hash表便于检索。

  1. void ActionManager::addAction(Action *action,Node *target,bool paused)
  2. {
  3. if(action == nullptr || target == nullptr)
  4. return;
  5.  
  6. tHashElement *element = nullptr;
  7. Ref *tmp = target;
  8. // _targets: target节点作为key,element作为value
  9. HASH_FIND_PTR(_targets,&tmp,element);
  10. if (! element)
  11. {
  12. element = (tHashElement*)calloc(sizeof(*element),1);
  13. element->paused = paused;
  14. // 当element销毁时 target将执行release
  15. target->retain();
  16. element->target = target;
  17. // 加入至当前hash表
  18. HASH_ADD_PTR(_targets,target,element);
  19. }
  20.  
  21. actionAllocWithHashElement(element);
  22. // 将action添加至element中
  23. ccArrayAppendObject(element->actions,action);
  24. // 动画关联至节点
  25. action->startWithTarget(target);
  26. }

addAction方法负责加入动画,update方法负责动画执行的核心逻辑。该方法完成了几个十分重要的工作:动画的更新操作step()、动画的移除与已完成动画的析构。

  1. // main loop
  2. void ActionManager::update(float dt)
  3. {
  4. for (tHashElement *elt = _targets; elt != nullptr; )
  5. {
  6. _currentTarget = elt;
  7. _currentTargetSalvaged = false;//标志是否release该动画
  8.  
  9. if (! _currentTarget->paused)
  10. {
  11. for (_currentTarget->actionIndex = 0; _currentTarget->actionIndex < _currentTarget->actions->num;
  12. _currentTarget->actionIndex++)
  13. {
  14. _currentTarget->currentAction = static_cast<Action*>(_currentTarget->actions->arr[_currentTarget->actionIndex]);
  15. if (_currentTarget->currentAction == nullptr)
  16. {
  17. continue;
  18. }
  19.  
  20. _currentTarget->currentActionSalvaged = false;
  21.  
  22. _currentTarget->currentAction->step(dt);
  23.  
  24. if (_currentTarget->currentActionSalvaged)
  25. {
  26. // The currentAction told the node to remove it. To prevent the action from
  27. // accidentally deallocating itself before finishing its step,we retained
  28. // it. Now that step is done,it's safe to release it.
  29. _currentTarget->currentAction->release();
  30. }
  31. else if (_currentTarget->currentAction->isDone())
  32. {
  33. _currentTarget->currentAction->stop();
  34.  
  35. Action *action = _currentTarget->currentAction;
  36. // Make currentAction nil to prevent removeAction from salvaging it.
  37. _currentTarget->currentAction = nullptr;
  38. removeAction(action);
  39. }
  40.  
  41. _currentTarget->currentAction = nullptr;
  42. }
  43. }
  44.  
  45. // elt,at this moment,is still valid
  46. // so it is safe to ask this here (issue #490)
  47. elt = (tHashElement*)(elt->hh.next);
  48.  
  49. // only delete currentTarget if no actions were scheduled during the cycle (issue #481)
  50. if (_currentTargetSalvaged && _currentTarget->actions->num == 0)
  51. {
  52. deleteHashElement(_currentTarget);
  53. }
  54. //if some node reference 'target',it's reference count >= 2 (issues #14050)
  55. else if (_currentTarget->target->getReferenceCount() == 1)
  56. {
  57. deleteHashElement(_currentTarget);
  58. }
  59. }
  60.  
  61. // issue #635
  62. _currentTarget = nullptr;
  63. }
  • 动画析构
    currentActionSalvaged 用以标志是否析构该动画。为什么需要标志?因为在step方法结束前可能存在移除action的操作。如果在移除动画时就析构动画,就会造成step方法的后续执行存在问题。cocos的做法是:移除action时暂时先暂时保存好这个action以使得step正常执行完成,等待完成后再进行析构。

    1. void ActionManager::removeActionAtIndex(ssize_t index,tHashElement *element)
    2. {
    3. Action *action = static_cast<Action*>(element->actions->arr[index]);
    4.  
    5. if (action == element->currentAction && (! element->currentActionSalvaged))
    6. {
    7. // 暂不析构 加上析构标志
    8. // 之所以要retain,因为后续的ccArrayRemoveObjectAtIndex会进行一次release
    9. element->currentAction->retain();
    10. element->currentActionSalvaged = true;
    11. }
    12.  
    13. ccArrayRemoveObjectAtIndex(element->actions,index,true);
    14.  
    15. // update actionIndex in case we are in tick. looping over the actions
    16. if (element->actionIndex >= index)
    17. {
    18. element->actionIndex--;
    19. }
    20.  
    21. if (element->actions->num == 0)
    22. {
    23. if (_currentTarget == element)
    24. {
    25. _currentTargetSalvaged = true;
    26. }
    27. else
    28. {
    29. deleteHashElement(element);
    30. }
    31. }
    32. }
  • step : 在时间线上更新action
    ActionManager中的update并非直接调用动画中的update完成动画关联节点的属性更新操作,而是间接调用step来执行。step方法内部将时间折算成0.0-1.0的动画进度,再将进度值传入到具体action的update中。这么做的好处有两个:1)每个action的update方法可以完全忽略时间关联,属性值的计算完全取决于进度值,这种理念使得计算十分便捷,很多时候我们只需计算起点与终点的偏移量,每个进度内的值基于偏移量进行一次线性插值即可;2)极易控制action的效果:如后面将提及的缓动函数:一个节点从某点移动至目标点,先加速、后匀速、后降速到达,此时缓动动画接收到动画的执行进度后利用缓动函数(其实就是一些简单的数学公式)进行一次非线性变化,最后将变换后的进度值供实际action使用。大家通过后续详细介绍的各种动画update函数会发现,将动画的累积执行时间转换为执行的进度会给计算带来很大的便利性。

    1. void ActionInterval::step(float dt)
    2. {
    3. if (_firstTick)
    4. // 第一次执行step 初始化变量
    5. _firstTick = false;
    6. _elapsed = 0;
    7. }
    8. else
    9. {
    10. // 累积时间
    11. _elapsed += dt;
    12. }
    13. // 对于[0,1]区间,MAX相当于0<=v,MIN相当于v<=1
    14. // 因此下述操作就是将进度 _elapsed/_duration 限值在[0,1]区间内
    15. float updateDt = MAX (0,// needed for rewind. elapsed could be negative
    16. MIN(1,_elapsed / _duration)
    17. );
    18. if (sendUpdateEventToScript(updateDt,this)) return;
    19. // 调用action的update,将进度作为参数传入
    20. this->update(updateDt);
    21. }

2 动画中的update机制

2.1 Sequence

  • 创建
    sequence动画将一些列自动化串联起来顺序执行,下一个动画总是等待上一个动画完成后再开始执行。每个sequence携带两个动作。当用多个子action创建一个sequence时,sequence内部对自动化进行两两叠加,组成多个sequence的嵌套。

    1. Sequence* Sequence::createWithVariableList(FiniteTimeAction *action1,va_list args)
    2. {
    3. FiniteTimeAction *now;
    4. FiniteTimeAction *prev = action1;
    5. bool bOneAction = true;
    6.  
    7. while (action1)
    8. {
    9. // 循环取子action 取出后与上一个动画组合成新的sequence
    10. now = va_arg(args,FiniteTimeAction*);
    11. if (now)
    12. {
    13. prev = createWithTwoActions(prev,now);
    14. bOneAction = false;
    15. }
    16. else
    17. {
    18. // If only one action is added to Sequence,make up a Sequence by adding a simplest finite time action.
    19. if (bOneAction)
    20. {
    21. // 值得借鉴的处理手法:即使只有一个action,也会创建一个空的action
    22. // 这能够保证一个sequence中总包含两个子动作,保持了统一性,避免后续不必要的麻烦。
    23. prev = createWithTwoActions(prev,ExtraAction::create());
    24. }
    25. break;
    26. }
    27. }
    28.  
    29. return ((Sequence*)prev);
    30. }
  • 串联逐个执行
    sequence中总进度区间由两个子动画组成。执行期间,初始化一个_split变量来记录action[0]的区间相对于总区间的占比。

    1. void Sequence::update(float t)
    2. {
    3. int found = 0; // 记录当前正在执行哪个动画:0 or 1
    4. float new_t = 0.0f; // 记录子action 完成进度
    5.  
    6. // 进度统计
    7. if( t < _split )//当前进度落在第一个动画区间内 表明正在执行第一个动画
    8. {
    9. // action[0]
    10. found = 0;
    11. if( _split != 0 )
    12. new_t = t / _split;// action[0]区间占比不为0 计算action[0]目前已完成的进度
    13. else
    14. new_t = 1; // action[0]区间占比为0(瞬时完成,如回调函数之类),action[0]进度升至1(已完成状态)
    15.  
    16. }
    17. else // 当前进度落在第二个动画区间内
    18. {
    19. // action[1]
    20. found = 1;
    21. if ( _split == 1 ) // _split=1 表明action[0]区间占比为1, action[2]区间占比为0
    22. new_t = 1; // action[1]进度直接升至1
    23. else
    24. new_t = (t-_split) / (1 - _split ); // 计算action[1]目前已完成进度
    25. }
    26.  
    27. // 执行相关action
    28. if ( found==1 )
    29. {
    30. if( _last == -1 ) // 当前正在执行action[1] 但上一次并未执行action[0]
    31. {
    32. // action[0] was skipped,execute it.
    33. _actions[0]->startWithTarget(_target);
    34. if (!(sendUpdateEventToScript(1.0f,_actions[0])))
    35. _actions[0]->update(1.0f); // 即刻完成第一个动画
    36. _actions[0]->stop();
    37. }
    38. else if( _last == 0 ) // action[0]已执行过
    39. {
    40. // switching to action 1. stop action 0.
    41. if (!(sendUpdateEventToScript(1.0f,_actions[0])))
    42. _actions[0]->update(1.0f); // 即刻完成
    43. _actions[0]->stop();
    44. }
    45. }
    46. else if(found==0 && _last==1 ) // 上一次执行了action[1],当前开始执行action[0],这一情形不处理
    47. {
    48. // Reverse mode ?
    49. // FIXME: Bug. this case doesn't contemplate when _last==-1,found=0 and in "reverse mode"
    50. // since it will require a hack to know if an action is on reverse mode or not.
    51. // "step" should be overridden,and the "reverseMode" value propagated to inner Sequences.
    52. if (!(sendUpdateEventToScript(0,_actions[1])))
    53. _actions[1]->update(0); // 不处理 直接跳过
    54. _actions[1]->stop();
    55. }
    56. // Last action found and it is done.
    57. if( found == _last && _actions[found]->isDone() )
    58. {
    59. return;
    60. }
    61.  
    62. // Last action found and it is done
    63. if( found != _last )
    64. {
    65. _actions[found]->startWithTarget(_target);
    66. }
    67. if (!(sendUpdateEventToScript(new_t,_actions[found])))
    68. _actions[found]->update(new_t);
    69. _last = found;
    70. }

2.2 Repeat

Repeat的update的执行分两中情形:1)总进度在下一次动作之前;2)总进度在下一次动作之后。对于第一种情形,计算当前正在执行动画的进度,计算公式为 local dt1 = fmodf(dt * _times,1.0f),dt为总进度,并基于该局部进度值更新当前动画。对于第二种情形,强制执行完当前动作,并开启下一个动作。这里有两个细节需要考虑:1. 如何正确结束最后一个动作;2. 如何放置前后两次动画不衔接导致的剧烈抖动。

  1. // issue #80. Instead of hooking step:,hook update:
  2. // since it can be called by any container action like Repeat,Sequence,Ease,etc..
  3. void Repeat::update(float dt)
  4. {
  5. if (dt >= _nextDt) // _nextDt:进入下一次重复动作需要完成的进度
  6. {
  7. while (dt >= _nextDt && _total < _times) // 进入下一个重复动作阶段 但还未完成所有动作 此处用while 可将所有instant action全部执行完成
  8. {
  9. if (!(sendUpdateEventToScript(1.0f,_innerAction)))
  10. _innerAction->update(1.0f); // 完成前一个动作
  11. _total++;
  12.  
  13. _innerAction->stop();
  14. _innerAction->startWithTarget(_target); // 开始下一个动作
  15. _nextDt = _innerAction->getDuration()/_duration * (_total+1); // 更新下一个动作进度
  16. }
  17.  
  18. // fix for issue #1288,incorrect end value of repeat
  19. if (dt >= 1.0f && _total < _times) // 总进度已经完成 最后一次动作还未结束 直接结束
  20. {
  21. if (!(sendUpdateEventToScript(1.0f,_innerAction)))
  22. _innerAction->update(1.0f); // 直接结束最后一次动作
  23.  
  24. _total++;
  25. }
  26.  
  27. // don't set an instant action back or update it,it has no use because it has no duration
  28. if (!_actionInstant)
  29. {
  30. if (_total == _times)
  31. {
  32. _innerAction->stop(); // 终止最后一次动作
  33. }
  34. else
  35. {
  36. // issue #390 prevent jerk,use right update
  37. // 理论上每一个action的update操作都在下面的else中完成 但完全在else中进行动作更新可能会使得动作在某个时刻发生剧烈抖动 因此无论是dt >= _nextDt还是dt < _nextDt,都对动画进行更新。
  38. if (!(sendUpdateEventToScript(dt - (_nextDt - _innerAction->getDuration()/_duration),_innerAction)))
  39. _innerAction->update(dt - (_nextDt - _innerAction->getDuration()/_duration));
  40. }
  41. }
  42. }
  43. else
  44. {
  45. if (!(sendUpdateEventToScript(fmodf(dt * _times,1.0f),_innerAction)))
  46. _innerAction->update(fmodf(dt * _times,1.0f)); // fmodf(dt * _times,1.0f):将总进度dt转换为局部进度(当前的action执行进度) _times可看作两个区间的缩放比
  47. }
  48. }

2.3 RepeatForever

Repeat更新的方式是

  1. void RepeatForever::step(float dt)
  2. {
  3. _innerAction->step(dt);
  4. if (_innerAction->isDone()) // 检测动作是否已完成
  5. {
  6. float diff = _innerAction->getElapsed() - _innerAction->getDuration(); // 当前Action时间超出部分
  7. if (diff > _innerAction->getDuration())
  8. diff = fmodf(diff,_innerAction->getDuration()); // 超出时间大于一个周期 取模校正
  9. _innerAction->startWithTarget(_target);
  10. // to prevent jerk. issue #390,1247
  11. _innerAction->step(0.0f);
  12. _innerAction->step(diff);
  13. }
  14. }

3 缓动动画

猜你在找的Cocos2d-x相关文章