Search code examples
c++cocos2d-xcocos2d-android

cocos2d-x Run parent action from child


I try to write a simple game using cocos2d-x library.

I created class (named Letter) to spawn sprite with random letter as a label and add a listener because I want to catch touch events. I've a function:

listener->onTouchEnded = [=](cocos2d::Touch* touch, cocos2d::Event* event)
{
    CCLOG("press");
    Letter::touchEvent(touch, event);
};

and action:

void Letter::touchEvent(cocos2d::Touch* touch, cocos2d::Event* event)
{
    this->removeFromParentAndCleanup(true);
    CCLOG("touched MySprite");
}

In my Layer I have a function to spawn instance of Letter class:

{
    CCLOG("new letter");
    Letter* _letter = Letter::create();

    addChild(_letter, 1);
}

And of course in init() i create a one letter:

this->createLetter();

Now, I want to create action which runs after touch to send some information (int) to my Layer, destroy Sprite and run createLetter(); again.

How can I do this? I tried create CC_CALLBACK_1 and something but I don't have idea what I need to do. :(

I'm not C++ master but I think I've basic knowledge about C++, I'm a system administrator, but I would like to try something net.

Thank you for help.


Solution

  • User this->getParent() in Latter class to access Layer class from and then call any method written there incuding createLetter() or any new method to pass integer.

    #

    YourLayerClass* layerObject = (YourLayerClass*)this->getParent();
    layerObject->sendData(3);
    layerObject->createLetter();
    this->removeFromParentAndCleanup(true);