cocos2d-x3.3 源码分析之-动作Action和ActionManager

cocos2d-x3.3 源码分析之-动作Action和ActionManager,第1张

概述写这篇文章,没有花我多少时间。但是由于我的笔记写在云笔记中,图片也多。csdn也不支持直接复制粘贴图片,可以说把笔记移植过来比我当初写还要费事,希望改进吧 从入口开始分析,我们来看看addaction函数,他接受一个动作,并绑定自己,是否暂停取决于节点的running属性。   我们来具体看看ActionManager这个类 class CC_DLLActionManager : public R

写这篇文章,没有花我多少时间。但是由于我的笔记写在云笔记中,图片也多。csdn也不支持直接复制粘贴图片,可以说把笔记移植过来比我当初写还要费事,希望改进吧



从入口开始分析,我们来看看addaction函数,他接受一个动作,并绑定自己,是否暂停取决于节点的running属性。

我们来具体看看ActionManager这个类

class CC_DLLActionManager : public Ref

{

public:

ActionManager(voID);

~ActionManager(voID);

voID addAction(Action *action,Node*target,bool paused);

voID removeAllActions();

voID removeAllActionsFromTarget(Node*target);

voID removeAction(Action *action);

voID removeActionByTag(int tag,Node*target);

voID removeAllActionsByTag(int tag,Node*target);

Action* getActionByTag(int tag,const Node*target) const;

ssize_tgetNumberOfRunningActionsInTarget(const Node *target) const;

voID pauseTarget(Node *target);

voID resuMetarget(Node *target);

Vector<Node*>pauseAllRunningActions();

voID resuMetargets(constVector<Node*>& targetsToResume);

voID update(float dt);

protected:

voID removeActionAtIndex(ssize_t index,struct _hashElement *element);

voID deleteHashElement(struct _hashElement*element);

voID actionAllocWithHashElement(struct_hashElement *element);

protected:

struct _hashElement *_targets;

struct_hashElement *_currentTarget;

bool _currentTargetSalvaged;

};

struct _hashElement*_targets;

struct_hashElement *_currentTarget;

如果是对定时器数据结构很熟悉的人没看到这个结构体应该不会陌生。的确,内部结构是相同的,只不过把之前的定时器对象改为现在的action.


类似的,每个hash节点一般由一个target标志,根据target找到节点。每个节点弱引用一个动作的array,也就是说,每个节点可以绑定多个动作,paused记录了当前动作的暂停状态。

下面来看看addAction函数:

voIDActionManager::addAction(Action *action,Node *target,bool paused)

{

CCASSERT(action != nullptr,"");

CCASSERT(target != nullptr,"");

//查找hash表,看看是否有相同的target,如果没有新建一个插入表中。

tHashElement *element = nullptr;

// we should convert it to Ref*,because wesave it as Ref*

Ref *tmp = target;

HASH_FIND_PTR(_targets,&tmp,element);

if (! element)

{

element =(tHashElement*)calloc(sizeof(*element),1);

element->paused = paused;

target->retain();

element->target = target;

HASH_ADD_PTR(_targets,target,element);

}

//为弱引用的数组分配内存

actionAllocWithHashElement(element);

//同一个动作结束前,如果被同一个节点包含两次,触发断言

CCASSERT(!ccArrayContainsObject(element->actions,action),"");

//将新的动作加入数组

ccArrayAppendobject(element->actions,action);

action->startWithTarget(target);

}

现在我们不介绍最后一句,因为我们需要回过头去看看Action及其子类

Action

class CC_DLL Action: public Ref,public Clonable

{

public:

//动作的默认tag,一般不可以用默认tag索引动作

static const int INVALID_TAG = -1;

/**

* @Js NA

* @lua NA

*/

virtual std::string description() const;

/** returns a clone of action */

virtual Action* clone() const

{

CC_ASSERT(0);

return nullptr;

}

/** returns a new action that performs theexactly the reverse action */

virtual Action* reverse() const

{

CC_ASSERT(0);

return nullptr;

}

//! return true if the action has finished

//判断动作是否结束

virtual bool isDone() const;

//! called before the action start. It willalso set the target.

//_taggetoriginTarget都赋值为新的绑定对象

virtual voID startWithTarget(Node *target);

/**

called after the action has finished. Itwill set the 'target' to nil.

important: You should never call"[action stop]" manually. Instead,use:"target->stopAction(action);"

*/

//动作结束后,调用该函数,把_target设置为null

virtual voID stop();

//! called every frame with it's deltatime. DON'T overrIDe unless you kNow what you are doing.

//类似定时器中的update函数

virtual voID step(float dt);

/**

called once per frame. time a value between0 and 1

For example:

- 0 means that the action just started

- 0.5 means that the action is in themIDdle

- 1 means that the action is over

*/

//类似定时器中的trigger函数

virtual voID update(float time);

inline Node* getTarget() const { return_target; }

/** The action will modify the targetpropertIEs. */

inline voID setTarget(Node *target) {_target = target; }

inline Node* getoriginalTarget() const {return _originalTarget; }

/** Set the original target,since targetcan be nil.

Is the target that were used to run theaction. Unless you are doing something complex,like ActionManager,you shouldNOT 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; }

CC_CONSTRUCTOR_ACCESS:

Action();

virtual ~Action();

protected:

Node*_originalTarget;

/** The "target".

The target will be set with the'startWithTarget' method.

When the 'stop' method is called,targetwill be set to nil.

The target is 'assigned',it is not'retained'.

*/

Node *_target;

/** The action tag. An IDentifIEr of theaction */

int_tag;

private:

CC_disALLOW_copY_AND_ASSIGN(Action);

};

isDownupdatestep这三个函数是虚函数,action并没有做什么实际的事情,所以我们现在还不知道他干了些什么,我们之后去看看具体的动作类就会清楚了。

_originalTarget_target这两者有什么区分现在也不清楚

我们来看看最重要的一个子类FiniteTimeAction

class CC_DLLFiniteTimeAction : public Action

{

public:

//! get duration in seconds of the action

inline float getDuration() const { return_duration; }

//! set duration in seconds of the action

inline voID setDuration(float duration) {_duration = duration; }

//

// OverrIDes

//

virtual FiniteTimeAction* reverse() constoverrIDe

{

CC_ASSERT(0);

return nullptr;

}

virtual FiniteTimeAction* clone() constoverrIDe

{

CC_ASSERT(0);

return nullptr;

}

CC_CONSTRUCTOR_ACCESS:

FiniteTimeAction()

: _duration(0)

{}

virtual ~FiniteTimeAction(){}

protected:

//! duration in seconds

float _duration;

private:

CC_disALLOW_copY_AND_ASSIGN(FiniteTimeAction);

};

只是增加了一个_duration属性,也就是动作的持续时间,应该是为了他的延时动作子类准备的。

我么接着看ActionInstant这个瞬时动作:

class CC_DLLActionInstant : public FiniteTimeAction //<NScopying>

{

public:

//

// OverrIDes

//

virtual ActionInstant* clone() constoverrIDe

{

CC_ASSERT(0);

return nullptr;

}

virtual ActionInstant * reverse() constoverrIDe

{

CC_ASSERT(0);

return nullptr;

}

virtual bool isDone() const overrIDe;

virtual voID step(float dt) overrIDe;

virtual voID update(float time) overrIDe;

};

瞬时动作类重写了step函数和isDown函数,其他的isDoneupdate函数并没有做出变化

step:


调用了update函数,并传入参数1。我们可以看看update函数的注释

called once perframe. 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

*/

1表示动作结束了

isDown:


isDown也返回true。我们或许会疑惑,不过接下来看了ActionManager中的update函数之后你就会明白了:

该函数在导演类的init函数中被注册到定时器:


该函数有最高的定时触发优先级,每一帧动作的运行都会触发该函数。

voIDActionManager::update(float dt)

{

for (tHashElement *elt = _targets; elt !=nullptr; )

{

_currentTarget = elt;

_currentTargetSalvaged = false;

if (! _currentTarget->paused)

{

// The 'actions' MutableArray maychange while insIDe this loop.

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 toldthe node to remove it. To prevent the action from

// accIDentallydeallocating itself before finishing its step,we retained

// it. Now that step isdone,it's safe to release it.

_currentTarget->currentAction->release();

} else

if (_currentTarget->currentAction->isDone())

{

_currentTarget->currentAction->stop();

Action *action =_currentTarget->currentAction;

// Make currentAction nilto 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 noactions were scheduled during the cycle (issue #481)

if (_currentTargetSalvaged &&_currentTarget->actions->num == 0)

{

deleteHashElement(_currentTarget);

}

}

// issue #635

_currentTarget = nullptr;

}

我们可以看到,step就相当于一个触发函数,而动作中的update函数就是触发函数中调用的函数,出发完成后,判断动作是否结束,如果结束调用stop函数,并移除动作。

我们现在可以回到之前的瞬时动作,update函数被传值为1isDown返回true,就很好理解了。

瞬时动作的基类没有实现update函数,我们以一个具体的瞬时动作来做例子:

class CC_DLL Show : public ActionInstant

{

public:

/** Allocates and initializes the action */

static Show * create();

//

// OverrIDes

//

virtual voID update(float time) overrIDe;

virtual ActionInstant* reverse() constoverrIDe;

virtual Show* clone() const overrIDe;

CC_CONSTRUCTOR_ACCESS:

Show(){}

virtual ~Show(){}

private:

CC_disALLOW_copY_AND_ASSIGN(Show);

};

重写了update函数:


接着看

voID ActionManager::update(float dt)中的那个removeAction函数:

好了一目了然,之前的_originTarget_targrt的区别也就知道了,_target是为了实现节点动作用的,二_target置为空之后,_originTarget便可以用来删除这个动作,动作删除后被release

好了,我们可以接着看延时动作了:

class CC_DLLActionInterval : public FiniteTimeAction

{

public:

/** how many seconds had elapsed since theactions started to run. */

inline float getElapsed(voID) { return_elapsed; }

//extension in GrIDAction

voID setAmplitudeRate(float amp);

float getAmplitudeRate(voID);

//

// OverrIDes

//

virtual bool isDone(voID) const overrIDe;

virtual voIDstep(float dt) overrIDe;

virtual voID startWithTarget(Node *target)overrIDe;

virtual ActionInterval* reverse() constoverrIDe

{

CC_ASSERT(0);

return nullptr;

}

virtual ActionInterval *clone() constoverrIDe

{

CC_ASSERT(0);

return nullptr;

}

CC_CONSTRUCTOR_ACCESS:

/** initializes the action */

bool initWithDuration(float d);

protected:

float_elapsed;

bool_firstTick;

};

_elapsed表示延时动作度过的时间

isDone:



很简单,只要度过的时间大于等于动作的生命周期就表示动作结束。

step:


很简单的定时逻辑,ActionManager中的update函数每一次出发后调用step函数,dt一般是每一帧的时间(大多数是1 /60)。每一次调用后,把dt加到_elapsed就可以做到计时了。update的参数被限制在0-1之间,具体的实现得看一个具体的例子:


这里的initWithDuration就是我们创建动作时候传递的动作生命周期。

update



很简单吧,每次变化后的属性重新设置给Node就达到了动画的目的。

我们接下来看看移除动作:

voID removeAction(Action *action)


移除很简单,找到绑定对象,从对象的动作数组中移除即可。

接下来看看Node中的stopAction函数:


函数原理都是一样的,拿其中一个举例:


间接调用了移除动作的函数。

注意事项:不要用action中的stop函数来停止动作,因为判断动作是否结束的标志是isDown函数,并且判断过程还是在动作执行之后。stop函数会将_target置为null,这样运行动作就会试图去修改_target的属性,导致程序奔溃。还有一点就是动作运行结束后会被删除,如果想多次运行动作,请retain

总结:

动作最重要的几个函数

isDown

step

stop

update

以及ActionManager::update

还有动作的重要属性:

_target

_origintarget

_elapsed

总结

以上是内存溢出为你收集整理的cocos2d-x3.3 源码分析之-动作Action和ActionManager全部内容,希望文章能够帮你解决cocos2d-x3.3 源码分析之-动作Action和ActionManager所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1052827.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存