Search code examples
c++cocos2d-x

To extract one char from label that are made from CClabelBMFont


I am trying to show slowly one char from string ,like novel game.

To do it,at first I wrote the code as follows using CCLabelBMFont to extract one char from string.

string str = "I like an apple";

CCLabelBMFont *label = CCLabelBMFont::create(str.c_str(), "font.fnt");

CCSprite *spr = (CCSprite*)label1->getChildByTag(0);
spr->setPosition(ccp(100, 100));

this->addChild(spr);

I want to show spr that are extracted from CCLabelBMFont in GameScene(this)

But I am getting the error as follows

CCAssert( child->m_pParent == NULL, "child already added. It can't be added again");

Why did such the error appear ? and How should I do?


Solution

  • Look at the method you are using and the error you get. You use getChildByTag(...) to get your sprite. So what you get is a child node of your CCLabelBMFont, meaning it has a parent. Your error says that this sprite cannot be added again as a child, because it already has a parent.

    I can't think of a straigthforward and sure way to achieve what you want, but here are some suggestions you may try :

    • Adding each letter as a seperate label - to be honest, this is really dumb as it unnecessarily multiplies your code and would use too much memory.
    • Making the children of your label invisible, and them make them visible one by one. When you create the label, iterate through its children and call setVisible(false) on them. Then schedule a call in which you will call setVisible(true) on subsequent children.
    • Possibly creating subclass of LabelBMFont and/or creating a custom action may be the most flexible way, but propably not the easiest.

    Let me know if anything is not clear!