Cocos2d autoremove sprite after animation

I am new to cocos2d and the development of iphone in general. I want to create some animation when some physical object with this sprite is destroyed (for example, to show a splash). And I want to make some kind of object that I will say: start the animation and destroy yourself when you are done. Then I want to forget about this object - it should be destroyed automatically when the animation is finished. What is the best way to do this?

+3
source share
2 answers

You can use CCSequence to create an action list. The first action you take should be your regular action (or sequence). The second action should be the CCCallFuncND action, where you can call the cleanup function and pass this sprite.

On top of my head, I would do something like this:

CCSprite* mySpriteToCleanup = [CCSprite spriteWithFile:@"mySprite.png"];
[self addChild:mySpriteToCleanup];

// ... do stuff

// start the destroy process
id action1 = [CCIntervalAction actionWithDuration:0];  // the action it sounds like you have written above.
id cleanupAction = [CCCallFuncND actionWithTarget:self selector:@selector(cleanupSprite:) data:mySpriteToCleanup];
id seq = [CCSequence actions:action1, cleanupAction, nil];
[mySpriteToCleanup runAction:seq];

and in the cleaning function:

- (void) cleanupSprite:(CCSprite*)inSprite
{
    // call your destroy particles here
    // remove the sprite
    [self removeChild:inSprite cleanup:YES];
}

You can add another action between these two actions, as well as to destroy particles for actions, instead of calling it at the end of the function.

+8
source

A convenient way is to use a custom action RemoveNodethat deletes the current CCNodeobject ( CCSpriteas well CCNode).

//Remove the node from parent and cleanup
@interface RemoveNode : CCActionInstant
{}
@end

@implementation RemoveNode
-(void) startWithTarget:(id)aTarget
{
    [super startWithTarget:aTarget];
    [((CCNode *)target_) removeFromParentAndCleanup:YES];
}

@end

Put it in the last CCSequence parameter. For example, a sprite will be deleted after disappearing:

[mySprite runAction:[CCSequence actions:
[CCFadeOut actionWithDuration:0.5], [RemoveNode action], nil]];
+3

Source: https://habr.com/ru/post/1774721/


All Articles