1
\$\begingroup\$

I'm writing my sBox2D game character's movement code, but my implementation of jumping is failing:

When I press the Jump key, the character jumps OK. However, when I press jump and another key (like the left arrow key) at the same time, it kind of blocks the jump from happening.

I'm using applyForceToCenter and setLinearVelocity to move the character.

What could the problem be?


Here's how I've bound keys trigger movement:

// press W key (aka Up key or BTNup)
if (RHInput.isDown(RHInput.BTNup)) {

    if(rhcl.isPlayerOnGround()) {
        toniBody.applyForceToCenter(0, 100, true );
        System.out.println("Toni jumps");
    }
}

// press A key (aka Left key or BTNleft)
if (RHInput.isDown(RHInput.BTNleft)) {

    if(rhcl.isPlayerOnGround()) {
        toniBody.setLinearVelocity(-5, 0);
        System.out.println("Toni walks left");
    }
    else {
        toniBody.setLinearVelocity(-1, 0);
    }
}
\$\endgroup\$
1
\$\begingroup\$

The setLinearVelocity method literally sets the Box2D body's x- and y-velocities to the given values.

That means if the parameter for x is set, the character will begin moving horizontally. However, if the parameter for y is zero, the character will stop moving vertically.

To fix this, you could either

  • pass the character's current y-velocity in the y-parameter, so it doesn't change to zero, or
  • use the applyForce (applyForceToCenter in jBox2D apparently) method, just as you've done for jumping, which only adds to or subtracts from existing velocities, instead of directly setting them.

The applyForce method is probably a better choice here, since Box2D is designed with the assumption that forces are what causes dynamic bodies to move. This usually makes collisions stabler. (Directly setting velocities is usually just used for kinematic bodies.)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.