开发者

cocos2d autoremove sprite after animation

开发者 https://www.devze.com 2023-01-25 12:52 出处:网络
I\'m new to cocos2d and to iphone development at all. I want to create some animation, when some physical object with it\'s sprite is destroyed (for example to show a splash). And i want to to make so

I'm new to cocos2d and to iphone development at all. I want to create some animation, when some physical object with it's sprite is destroyed (for example to show a splash). And i want to to make some object i will say to: run th开发者_运维知识库e animation and destroy yourself when done. Then i want to forget about this object - it should be destroyed automatically when animation is finished. What is the best way to do it?


You can use CCSequence to create a list of actions. The first action you do should be your regular action (or sequence). The second action should be CCCallFuncND action, where you can call a cleanup function and pass the given sprite.

Off the top of my head I'd 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 cleanup function:

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

You could add in another action between these two actions as well for your destroy particle actions instead of calling that in the end function.


The convenient way is using custom RemoveNode action, that removes the running CCNode object (CCSprite is also 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

Place it in the CCSequence last parameter. For example, sprite will be removed after fade out:

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

精彩评论

暂无评论...
验证码 换一张
取 消