您的位置:首页 > 移动开发 > Cocos引擎

20、Cocos2dx 3.0游戏开发找小三之Cocos2d-x的动作机制:嘻,善哉!技盖至此乎?

2014-06-13 13:54 411 查看
重开发者的劳动成果,转载的时候请务必注明出处:http://blog.csdn.net/haomengzhu/article/details/30480379

庖丁为文惠君解牛,手之所触,肩之所倚,足之所履,膝之所踦, 砉然向然,奏刀騞然,莫不中音。
-----先秦·庄周《庄子·养生主》



当学习整套动作的用法之后,我不禁感觉很好奇,究竟动作机制在 Cocos2d-x 里是如何实现的?
那我们就如同庖丁解牛一般,一起来一步步揭开动作机制的神秘面纱吧。

Action动作类的结构
首先,来分析一下 Action 及其子类(主要是 FiniteTimeAction 及其子类)的一些成员函数和成员变量,
我们将通过这 些变量和函数来分析动作的基本流程。
从 Action 的定义中可以看到:
/**
@brief Base class for Action objects.
*/
class CC_DLL Action : public Ref, public Clonable
{
public:
/// Default tag used for all the actions
static const int INVALID_TAG = -1;
/**
* @js NA
* @lua NA
*/
virtual std::string description() const;

/** returns a clone of action */
virtual Action* clone() const = 0;

/** returns a new action that performs the exactly the reverse action */
virtual Action* reverse() const = 0;

//! return true if the action has finished
virtual bool isDone() const;

//! called before the action start. It will also set the target.
virtual void startWithTarget(Node *target);

/**
called after the action has finished. It will set the 'target' to nil.
IMPORTANT: You should never call "[action stop]" manually. Instead, use: "target->stopAction(action);"
*/
virtual void stop();

//! called every frame with it's delta time. DON'T override unless you know what you are doing.
virtual void step(float dt);

/**
called once per frame. time a value between 0 and 1

For example:
- 0 means that the action just started
- 0.5 means that the action is in the middle
- 1 means that the action is over
*/
virtual void update(float time);

inline Node* getTarget() const { return _target; }
/** The action will modify the target properties. */
inline void setTarget(Node *target) { _target = target; }

inline Node* getOriginalTarget() const { return _originalTarget; }
/** Set the original target, since target can be nil.
Is the target that were used to run the action. Unless you are doing something complex, like ActionManager, you should NOT call this method.
The target is 'assigned', it is not 'retained'.
@since v0.8.2
*/
inline void setOriginalTarget(Node *originalTarget) { _originalTarget = originalTarget; }

inline int getTag() const { return _tag; }
inline void setTag(int tag) { _tag = tag; }

protected:
Action();
virtual ~Action();

Node *_originalTarget;
/** The "target".
The target will be set with the 'startWithTarget' method.
When the 'stop' method is called, target will be set to nil.
The target is 'assigned', it is not 'retained'.
*/
Node *_target;
/** The action tag. An identifier of the action */
int _tag;

private:
CC_DISALLOW_COPY_AND_ASSIGN(Action);
};


继承自 Action 的 FiniteTimeAction 主要新增了一个用于保存该动作总的完成时间的成员变量: 
float _duration。
对于FiniteTimeAction 的两个子类 ActionInstant 和 ActionInterval,前者没有新增任何函数和变量,
而后者增加了两个成员变量    float_elapsed;和bool_firstTick;
其中 _elapsed是从动作开始起逝去的时间,而 _firstTick是一个控制变量。

再来看下动作的更新:
当我们对 Node 调用 runAction(Action* action)方法时,
动作管理类 Action Manager(它是一个单例对象)会将新的 Action 和对应的目标节点添加到其管理的动作表中。
在 ActionManager 的 addAction 方法中,我们将动作添加到动作队列之后,
就会对该 Action 调用成员函数startWithTarget(Node* pTarget)来绑定该动作的执行者。
而在 Action 的子类中(如 ActionInterval),还初始化了一些参数:
来看ActionInterval的startWithTarget方法:
virtual void startWithTarget(Node *target) override;
void ActionInterval::startWithTarget(Node *target)
{
FiniteTimeAction::startWithTarget(target);
_elapsed = 0.0f;
_firstTick = true;
}


当这些准备工作都完成后,
每一帧刷新屏幕时,系统都会在 ActionManager 中遍历其动作表中的每一个动作,
并调用该动作的 step(float dt)方法。
step 方法主要负责计算 _elapsed 的值,并调用 update(float time)方法,相关代码如下
void ActionInterval::step(float dt)
{
if (_firstTick)
{
_firstTick = false;
_elapsed = 0;
}
else
{
_elapsed += dt;
}

this->update(MAX (0, // needed for rewind. elapsed could be negative
MIN(1, _elapsed /
MAX(_duration, FLT_EPSILON) // division by 0
)
)
);
}

传入 update 方法的 time 参数表示逝去的时间与动作完成需要的时间的比值,
是介于 0 和 1 之间的一个数,即动作完成的 百分比。 

ActionInterval并没有进一步实现update方法。 
下面我们继续以继承自ActionInterval的RotateTo动作的update方法为例,
分析 update 函数是如何实现的,其实现代码如下:
void RotateTo::update(float time)
{
if (_target)
{
_target->setRotationSkewX(_startAngleX + _diffAngleX * time);
_target->setRotationSkewY(_startAngleY + _diffAngleY * time);
}
}


到这里,我们已经能看出 Cocos2d-x 的动作机制的整个工作流程了。
在 RotateTo 中,最终完成的操作是修改目标节点 的 Rotation 属性值,更新该目标节点的旋转属性值。 
最后,在每一帧刷新结束后,在 ActionManager 类的 update 方法中都会检查动作队列中每一个动作的 isDone 函数是否返回 true。如果返回
true,则动作已完成,将其从队列中删除。

isDone函数的代码如下:
virtual bool isDone(void) const override;
bool ActionInterval::isDone(void) const
{
return _elapsed >= _duration;
}


对于不同的动作类,虽然整体流程大致都是先调用 step 方法,然后按照各个动作的具体定义来更新目标节点的属性,但是不同动作的具体实现会有所不同。
例如,RepeatForever 动作的 isDone 函数始终返回 false,因为它是永远在执行的动作;
又如 ActionInstant 及其子类的 step 函数中,向 update 传递的参数值始终是 1,因为瞬时动作会在下一帧刷新后完成,不需要多次执行
update。

ActionManager的工作原理
了解了Action 在每一帧中如何被更新之后,我们不妨回头看看动作管理类 ActionManager 的工作原理。
在对Director 进行初始化时,也会对 ActionManager 进行初始化。
下面的代码是 Director::init()方法中的一部分:
// action manager
//动作管理器
_actionManager = new ActionManager();
_scheduler->scheduleUpdate(_actionManager, Scheduler::PRIORITY_SYSTEM, false);


可以看到,在 ActionManager 被初始化后,马上就调用了定时调度器 Scheduler 的 scheduleUpdate 方法。
在 scheduleUpdate函数中,我们为 ActionManager 注册了一个定期更新的服务,这意味着动作的调度与定时
器的调度都统一受到 Scheduler 的控制。
具体地说,我们可以方便地同时暂停或恢复定时器与动作的运行,而不必考虑它们不同步的问题。
Scheduler 在每一帧更新时,都会触发 ActionManager 注册的 update 方法。
从下面给出的 ActionManager::update方法的代码可以看到,
ActionManager 在这时对每一个动作都进行了更新。
与调度器 Scheduler 类似的一点是,为了防止动作调度过程中所遍历的表被修改, 
Cocos2d-x 对动作的删除进行了仔细地处理, 保证任何情况下都可以安全地删除动作:
// main loop
void ActionManager::update(float dt)
{
//枚举动作表中的每一个目标节点
for (tHashElement *elt = _targets; elt != nullptr; )
{
_currentTarget = elt;
_currentTargetSalvaged = false;

if (! _currentTarget->paused)
{
// The 'actions' MutableArray may change while inside this loop.
//枚举目标节点对应的每一个动作
//actions 数组可能会在循环中被修改,因此需要谨慎处理
for (_currentTarget->actionIndex = 0; _currentTarget->actionIndex < _currentTarget->actions->num;
_currentTarget->actionIndex++)
{
_currentTarget->currentAction = (Action*)_currentTarget->actions->arr[_currentTarget->actionIndex];
if (_currentTarget->currentAction == nullptr)
{
continue;
}

_currentTarget->currentActionSalvaged = false;

//触发动作更新
_currentTarget->currentAction->step(dt);

if (_currentTarget->currentActionSalvaged)
{
// The currentAction told the node to remove it. To prevent the action from
// accidentally deallocating itself before finishing its step, we retained
// it. Now that step is done, it's safe to release it.
_currentTarget->currentAction->release();
} else
if (_currentTarget->currentAction->isDone())
{
_currentTarget->currentAction->stop();

Action *action = _currentTarget->currentAction;
// Make currentAction nil to prevent removeAction from salvaging it.
_currentTarget->currentAction = nullptr;
removeAction(action);
}

_currentTarget->currentAction = nullptr;
}
}

// elt, at this moment, is still valid
// so it is safe to ask this here (issue #490)
elt = (tHashElement*)(elt->hh.next);

// only delete currentTarget if no actions were scheduled during the cycle (issue #481)
if (_currentTargetSalvaged && _currentTarget->actions->num == 0)
{
deleteHashElement(_currentTarget);
}
}

// issue #635
_currentTarget = nullptr;
}


郝萌主友情提示:
庖丁解牛,神乎其技,对于学习,要知其然,更要知其所以然、、、
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐