Search code examples
c++spritecocos2d-x

update sprite position with schedule function


In my game I have an animated sprite. I added box2d to my game to add gravity. now I want to update my sprite's position using the schedule function. I got it working with objective-C, but I want it to be a multiplatform game so now I'm trying it in c++.

In my init I have the following line:

this->schedule(cocos2d::SEL_SCHEDULE(View::tick(1.0f)));

and the method tick:

void View::tick(float dt) {
world->Step(dt, 10, 10);
for(b2Body *b = world->GetBodyList(); b; b=b->GetNext()) {
if(b->GetUserData() != NULL) {
}
}
}

I get the following error on the line in my init: "cannot cast from type ' void' to member pointer type 'coco2d::sel_schedule' (aka void coco2d::CCobject::*)(float)

I have no idea what to do now. I tried to google, but everyone either uses objective - c or schedule_selector (which apparently doesn't work anymore)

Thanks in advance


Solution

  • You should probably not be using the schedule function to update a single sprite.

    In your scene class, override the virtual method for update(...):

    virtual void update(float dt)
    {
        CCLOG("This was called.");
        // Do updates for everything in the scene you need to call on a tick.
    }
    

    Also, override onEnter() and onExitTransitionDidStart(). In the first, call scheduleUpdate to set up your scene for automatically being called on a tick. In the second, call unscheduledUpdate (as the scene is exiting) to stop the updates.

    void IntroScene::onEnter()
    {
       CCScene::onEnter();
       scheduleUpdate();
    }
    
    void IntroScene::onExitTransitionDidStart()
    {
       CCScene::onExitTransitionDidStart();
       unscheduleUpdate();
    }
    

    Doing it this way gives you explicit control over what gets updated when...you only have a single function called during an update cycle.

    HOWEVER, if you really want to do it:

    Declare your custom updater like this:

    void IntroScene::myUpdate(float dt)
    {
       CCLOG("Also called");
    }
    

    Schedule it like this:

    schedule(schedule_selector(IntroScene::myUpdate), 1.0f);
    

    Unschedule it like this:

    unschedule(schedule_selector(IntroScene::myUpdate));
    

    ** NOTE ** As far as I know, you can only "schedule" objects derived from CCNode.

    Was this helpful?