0
votes

I have a scene init with physics and i have a character sprite with a physics body, then I have a static ground sprite with a physics body. That all works fine so my next step was to move my character. Now I assumed that if I just updated my characters X position the character would move and stay on the ground but if the ground drops off the character does not drop it just floats, how do i move my character sprite and have it stay on the ground at all times? The code for my update function is below

void LevelOne::update(float delta)
{
    if (mJoystick->isActive())
    {
        Vec2 scaledVelocity = mJoystick->getVelocity() * 240;
        Vec2 updatedPosition = Vec2(mCharacter->getPosition().x + scaledVelocity.x 
                                    * delta, mCharacter->getPosition().y);

    mCharacter->setPosition(updatedPosition);

    if (mJoystick->getVelocity().x < 0)
    {
        mCharacter->setFlippedX(false);
    }
    else
    {
        mCharacter->setFlippedX(true);
    }
}
1

1 Answers

0
votes

Following Steps can solve your problem-

1) Have you set the Gravity like gravity.Set(0.0f, -10.0f), y should be in negative.

2) Set you Character Sprite is Dynamic.

3) code should be in update method.

    int32 velocityIterations = 1;
    int32 positionIterations = 1;
    world -> Step(dt, velocityIterations, positionIterations);
    for (b2Body* b = world -> GetBodyList(); b; b = b -> GetNext()) {
        if (b -> GetUserData() != NULL) {
            CCSprite *myActor = (CCSprite*) b -> GetUserData();
            if(myActor != NULL) {
                myActor->setPositionY( b -> GetPosition().y * PTM_RATIO);
                myActor->setRotation(-1 * CC_RADIANS_TO_DEGREES(b -> GetAngle()));
            }

        }
    }