Search code examples
androidwindowscocos2d-iphonebox2dcocos2d-x

Cocos2dx : Help needed for the moving platform game


I am trying to make a platform game in which, the platform moves from right side of the screen to the left side of the screen. And the hero is initialized in the middle of the screen.

The platform is b2_kinematicBody while the hero is the b2_dynamic body. Once I jump on the platform the hero starts moving to the left side of the screen as well with the platform.

My question is : How do I prevent the hero from moving to the left side of the screen ? I want to keep the hero to the middle of the screen at all times, to give the impression that he is walking as all the platforms are moving behind him to the left.

Please help. Any guidance would be appreciated. Thanks


Solution

  • You may have a main void CCNode for all your scenario platforms/objects, inside which will also be your hero CCSprite.

    Then, you just need to move the void CCNode according to hero's movement, so that hero sprite will always be at the center (while you don't reach scenario edges), and the scenario will move instead. Something like this.-

    float positionX = heroSprite->getPosition().x;
    if (positionX > 0) {
        float offset = positionX;
        voidNode->setPosition(ccp(MAX(-offset, -TOTAL_LEVEL_WIDTH + CANVAS_WIDTH), voidNode->getPosition().y));
    }
    

    Hope it helps.

    Note: This code supposes the center of the screen is at point (0, 0).