XBXSlagHeap
XBXSlagHeap

Reputation: 174

How To Retrieve Actions From Sprite In cocos2d

I have a CCSprite that I'm using in a scene and have created multiple CCAnimation actions to apply to it all using a single CCSpriteFrameCache sharedSpriteFrameCache. While everything is working and I'm able to switch between animations, I feel like I'm doing poorly and would like to simplify my code by retrieving the running action(s) on the CCSprite to stop them individually before running the next action on it.

To help create some context, lets assume the following situation:

The approach I'm using to accomplish this is as follows:

  1. Place CCSprite as a child in the scene.
  2. Tell the sprite to run an action using: [self runAction:actionWalkRight];
  3. When I want to change the action after someone touches, I have a method called stopAllAnimationActions which I call before I apply a new action that stops any animation action no matter what's running. Basically lists ALL the CCAnimation/CCActions I have defined and stops each one individually since I don't want to use stopAllActions. as follows: [self stopAction:actionWalkRight]; [self stopAction:actionWalkLeft]; [self stopAction:actionSitForward];
  4. Then I apply the new animation after the above method fires using: [self runAction:actionWalkLeft];

While this works, it just seems like a poor design to stop items that I know aren't running just because I don't know exactly what is running. So just looking for advice and the best recommended practice to do something like this within very complex situations so tracking every possible situation is difficult. Any feedback would be appreciated.

Upvotes: 0

Views: 1132

Answers (2)

Saikat
Saikat

Reputation: 2623

When creating the actions set the tag of that action with a constant:

actionWalkRight.tag= kCurrentAction;
[self runAction:actionWalkRight];

Then, retrieve the running action by that tag and stop it.

[self stopActionByTag:kCurrentAction];

Upvotes: 1

johnbakers
johnbakers

Reputation: 24750

I recommend you simplify your process and take advantage of the native Cocos features, including stopAllActions. Don't re-use actions, always create them from scratch as it has been well discussed among Cocos developers that re-using actions can be buggy.

Cocos is well optimized and features like stopAllActions are not performance hogs. It would probably be faster than your approach, actually.

Upvotes: 1

Related Questions