Remove sprite after use

Hi guys, I am making a clone of a flappy bird and I am facing this problem, my game crashes after I try to delete a sprite after animating it.

I have a SpawnPipe function that is called from GameScene when pipes need to be spawned. In this function, I registered the animation of the pipe movement and its removal after the movement, but the game crashes.

topPipe->setPosition(Point(visibleSize.width + topPipe->getContentSize().width + origin.x + 
(visibleSize.width / 2), topPipePosition));

bottomPipe->setPosition(Point(topPipe->getPositionX() - topPipe->getContentSize().width * 2, 
topPipePosition - (Sprite::createWithSpriteFrameName("bird1.png")->getContentSize().height * 
PIPE_GAP) * cocos2d::random(1.0, 2.0) /*- topPipe->getContenSize().height*/));

layer->addChild(topPipe);
layer->addChild(bottomPipe);

auto fadeIn = FadeIn::create(0.3f);

auto topPipeAction = MoveBy::create(PIPE_MOVEMENT * visibleSize.width * 2, Point(-visibleSize.width  * 3, 0));
auto bottomPipeAction = MoveBy::create(PIPE_MOVEMENT * visibleSize.width * 2, Point(-visibleSize.width * 3, 0));

auto seqTop = Sequence::create(fadeIn, topPipeAction, CallFunc::create([&topPipe, &bottomPipe, layer]()
{
    layer->removeChild(topPipe, true);
}), nullptr);

auto seqBot = Sequence::create(fadeIn->clone(), bottomPipeAction, CallFunc::create([&topPipe, &bottomPipe, layer]()
{
    layer->removeChild(bottomPipe, true);
}), nullptr);

topPipe->runAction(seqTop);
bottomPipe->runAction(seqBot);

Help me please)

Try removeFromParentAndCleanup()

1 Like

A debugger would have shown you the problem in a few seconds, because you already know when it crashes, and from that you can deduce where it crashes.

auto seqTop = Sequence::create(fadeIn, topPipeAction, CallFunc::create([&topPipe, &bottomPipe, layer]()
{
    layer->removeChild(topPipe, true); // It crashes here, right? Put a breakpoint here and all will be revealed.
}), nullptr);

The issue is most likely this:

CallFunc::create([&topPipe, &bottomPipe, layer]

You’re capturing by reference, so when the function eventually gets called, topPipe and bottomPipe are no longer holding the right values.

They need to be captured by value:
CallFunc::create([topPipe, bottomPipe, layer]

1 Like

Simple change CallFunc to RemoveSelf. It will be removed by Action when reach the index of Sequence.

auto seqTop = Sequence::create(fadeIn, topPipeAction, RemoveSelf::create(), nullptr);
auto seqBot = Sequence::create(fadeIn->clone(), bottomPipeAction, RemoveSelf::create(), nullptr);
1 Like

Thanks guys!!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.