1
\$\begingroup\$

I'm trying to implement gravity and the ability for the player to jump in my 2D LibGDX game. At the moment, I have two handlers: One for gravity and one for keyboard input

@Override
public boolean keyDown(int keycode) {
    // Jumping
    if (keycode == Input.Keys.SPACE) {
        player.getVelocity().add(0, 32);
    }
    return false;
}

@Override
public void update(float deltaTime) { // Update is called every frame
    // Gravity handling
    player.getVelocity().add(0, -50 * deltaTime);

    // Update the position of the player
    player.getPosition().add(player.getVelocity().scl(deltaTime));
}

I thought this would work well, however the jumping is very jittery and abrupt. I would like to make it more smooth.

\$\endgroup\$
  • \$\begingroup\$ could you also post where you are updating the position of the player? \$\endgroup\$ – spectacularbob May 17 '16 at 16:40
  • \$\begingroup\$ Ah I don't know how I missed that. I've updated the original post with that. It's just one line after I add the gravity velocity. It now occurs to me that my issue may be related to updating the position directly after adding gravity, but I'm not sure how else to do it. \$\endgroup\$ – Panda May 17 '16 at 21:58
  • \$\begingroup\$ why you do not experiment the box2d ? you would not have had to implement a calculation for the launch oblique, or worry with the conflit of forces \$\endgroup\$ – Leo Lima May 19 '16 at 3:46
  • \$\begingroup\$ I'm just getting into game development and want to take it slow. Box2D has many concepts that I'm not yet familiar with. I definitely plan to learn it, but not at this stage. \$\endgroup\$ – Panda May 20 '16 at 2:13
1
\$\begingroup\$

My guess to why it is choppy is because scl() is permanently scaling your velocity by deltaTime each update call. Since deltaTime varies a little from frame to frame, this causes the choppiness. Change the position update to

float velocityX = player.getVelocity().x;    
float velocityY = player.getVelocity().y;
player.getPosition().add(velocityX * deltaTime,velocityY * deltaTime);

The only reason that scl() returns a Vector2 is for chaining. It is still the original Vector2 that was scaled.

\$\endgroup\$
0
\$\begingroup\$

I've solved the problem after a bit more analysis. In addition to the suggestion by spectacularbob, I forgot about a line of code that applies damping to the players velocity to make him slide less. This worked well for movement on the x-axis, but resulted in the jittery jumping on the y-axis. I simply changed the following:

player.getVelocity().scl(player.dampingSpeed);

to only apply the damping on the x velocity:

player.getVelocity().x *= player.dampingSpeed;
\$\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.