【问题标题】:cocos2d autoremove sprite after animationcocos2d 动画后自动删除精灵
【发布时间】:2023-03-30 19:53:01
【问题描述】:

我是 cocos2d 和 iphone 开发的新手。我想创建一些动画,当一些带有它的精灵的物理对象被破坏时(例如显示飞溅)。我想做一些我会说的对象:运行动画并在完成后摧毁自己。然后我想忘记这个对象 - 当动画完成时它应该自动销毁。最好的方法是什么?

【问题讨论】:

    标签: iphone objective-c c cocos2d-iphone


    【解决方案1】:

    您可以使用 CCSequence 创建操作列表。你做的第一个动作应该是你的常规动作(或序列)。第二个动作应该是 CCCallFuncND 动作,您可以在其中调用清理函数并传递给定的精灵。

    在我的脑海中,我会做这样的事情:

    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];
    

    在清理功能中:

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

    您也可以在这两个动作之间添加另一个动作以用于销毁粒子动作,而不是在结束函数中调用它。

    【讨论】:

    • 非常好。在 cocos2D 2.0 中还可以使用块:CCAction *cleanupAction = [CCCallBlock actionWithBlock:^{ [mySpriteToCleanup removeFromParentAndCleanup:YES]; }];
    【解决方案2】:

    方便的方法是使用自定义RemoveNode 操作,删除正在运行的CCNode 对象(CCSprite 也是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
    

    把它放在CCSequence的最后一个参数中。例如,sprite 会在淡出后被移除:

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

    【讨论】:

    • 在 Cocos2d 2.1 中,我不得不将其调整为 [(CCNode *)_target removeFromParentAndCleanup:YES];
    猜你喜欢
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 2012-07-08
    • 2014-05-16
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多