Search code examples
ioscocos2d-iphonecocos2d-x

class instance changed in callback method comparing to the main instance


in cpp:

void Character::jump(CCLayer *layer){
    if (this->isAnimationPlaying) return;
    up_or_down = UP;
    body->runAction(CCSequence::actions(
                                        CCMoveBy::actionWithDuration(0.5, ccp(0, 50)),
                    CCCallFuncND::actionWithTarget(body, callfuncND_selector(Character::upDownDone), this),
//                                        CCCallFuncN::actionWithTarget(body, callfuncN_selector(Character::upDownDone)),
                    NULL));
    this->isAnimationPlaying = true;
}

void Character::upDownDone(CCNode *node, CCObject *ob){
   this->isAnimationPlaying = false;   // *this is different from the this(class instance) in jump method, seems this in upDownDone is a new created instance*
}

So How can I get the class instance in a callback method? And can I make the this same for the main class instance and the callback's class instance?

EDIT:

Character is a class which has no parent class, and body is a member variable which is an instance of CCSprite.

Thanks.


Solution

  • because you are using body to call the function Character::upDownDone.

    you should use this to call it.

    CCCallFuncND* callFunc = CCCallFuncND::actionWithTarget(first_arg, secend_arg, third_arg);
    body->runAction(callFunc);
    

    assume your secend_arg is callfuncND_selector(Character::upDownDone)

    then,

    the first_arg is the caller, ie. the class instance who calls this function, in your code is body. but actually it should be this, or any instance of Charactor class

    the CCNode* node (the first para that is been passed to your calling function) is the action runner, ie. body in your code. because you are using body->runAction()

    the CCObject* obj (the second para that is been passed to your calling function) is a void pointer which is exactly the same with third_arg.

    another way is use

    void Character::upDownDone(CCNode *node, void *ob){
        (Character*)ob->isAnimationPlaying = false;
    }