arunkumar
arunkumar

Reputation: 67

remove a sprite in cocos2d-x

I am new to cocos2d-x.I am developing a game in xcode using cocos2d-x. In my game, i have sprite animation(man) and moving obstacles and coins. I making collision with sprite animation & coins. When i get 10 coins, i am adding a life(adding a sprite for life). My question is when collision is happening between sprite animation(man) & obstacles, life should decrease(i mean life sprite should remove) but it is not removed. I am using the following code.

if(coincount%10==0)
{
  lifecount=lifecount+1;
}
if(lifecount==1)
{
 life = CCSprite::create("life.png");
 life->setPosition( ccp(winwsize/2, winhsize/1.08) );
 this->addChild(life, 5);
}
else if(lifecount==2)
{
 life1 = CCSprite::create("life.png");
 life1->setPosition( ccp(winwsize/1.8, winhsize/1.08) );
 this->addChild(life1, 5);
}
else if (lifecount==3)
{
 life2 = CCSprite::create("life.png");
 life2->setPosition( ccp(winwsize/1.6, winhsize/1.08) );
 this->addChild(life2, 5);
}

if (manRect.intersectsRect(obs5Rect))
{
if(lifecount>=1)
{
 lifecount=lifecount-1;
 this->scheduleOnce(schedule_selector(PlayScene::remove),0.5f);
}

void PlayScene::remove()
{
if(lifecount==0)
{
    this->removeChild(life, true);
}
else if(lifecount==1)
{
this->removeChild(life1, true);
}
else if(lifecount==2)
{
this->removeChild(life2, true);
}

But sprite is not removing, when obstacle collide with sprite animation(man). Please anyone could help me to find the solution. Thanks.

Upvotes: 0

Views: 3503

Answers (3)

Hitesh Rajyaguru
Hitesh Rajyaguru

Reputation: 87

First setTag on Sprite like:
Sprite->setTag(111);
removeChildByTag(111);

       OR

Sprite->removeFromParent();

Upvotes: 2

GameDeveloper
GameDeveloper

Reputation: 1029

I think your best bet is to do:

life1->setTag(99); // i made up the 99

and then when you want to remove it use removeChildByTag(99);

Upvotes: 0

Losiowaty
Losiowaty

Reputation: 8006

It seems that the problem is in your remove function. You create sprites life, life1, life2 when lifeCount is 1, 2 or 3 respectively. But in your remove method, you check if lifeCount is 0, 1 or 2. If it were 3, none of the sprites would be removed, as none of the conditions are met. Also you do not deacrease lifeCount anywhere.

Solution :
Either add --lifecount; at the beginning of remove(), or change your conditions appropriately and decrease the counter at the end.

Suggestions :
If I may suggest an improvemt to your code : you should keep your life sprites in an array, so that when you decide to add the possibility to have more lives it will be much easier.

Let me know if anything is not clear.

Upvotes: -1

Related Questions