1
\$\begingroup\$

I'm creating a simple jumper game in Libgdx that makes the player jump over obstacles in order to stay alive.

The only problem is that the collision detection for when the player just touches the ground, it:

1) Looks a little bit like there's a hitch in the repainting (because it tends to go a y axis little too far before being brought back to above 0).

2) Can't jump right away again (a very small, but annoying delay).

Here is the code that checks for collisions:

public void update(float dt) {
    if (location.y < screenBounds.y) {
        location.add(MOVEMENT * dt, 0, 0);
        velocity.y = 0;
        location.y = 0 + dt;
    } else {
        velocity.add(0, GRAVITY, 0);
        velocity.scl(dt);
        location.add(MOVEMENT * dt, velocity.y, 0);
        velocity.scl(1 / dt);
    }

} 

I know why, it does this though:

LOCATION BEFORE RESETTING -0.45871875
LOCATION AFTER RESETTING 0.017244088

It takes too long to realize that the location on the y axis is below 0. This creates a hitch as well as a small delay between the times where it lets the player jump again.

I don't know how to fix this problem. I've looked at many posts that discuss collision detection, but none address the same problem I'm having.

For example, these tell me to do what I'm currently doing:

Collision detection Collision detection in libgdx

But they both don't solve my issue.

Any help would be greatly appreciated.

\$\endgroup\$
2
  • \$\begingroup\$ Instead of location.y < screenBounds.y try location.y <= screenBounds.y \$\endgroup\$
    – Jax
    Commented Apr 18, 2016 at 18:50
  • \$\begingroup\$ I tried it, but it didn't really help. Thanks for the suggestion though \$\endgroup\$
    – Eames
    Commented Apr 18, 2016 at 19:00

1 Answer 1

1
\$\begingroup\$

I assume that you are calling update() once every frame, before you draw the frame.

Your problem is that you are doing either the collision correction or the movement every frame. You need to do both. What's happening is:

  1. Your character checks if it is below the screen bounds, it isn't
  2. So it moves below the screen bounds, draws for one frame below the screen bounds
  3. Then, on the next frame checks again if it is below the screen bounds, it is, so it corrects itself

Try this

public void update(float dt) {
    //Let the player intially move wherever they want
    velocity.add(0, GRAVITY, 0);
    velocity.scl(dt);
    location.add(MOVEMENT * dt, velocity.y, 0);
    velocity.scl(1 / dt);

    //If they ended up below the screen, move them up and cancel out gravity
    if (location.y < screenBounds.y) {
        velocity.y = 0;
        location.y = screenBounds.y;
    }
}

Also, you probably don't need the scl() calls. Instead, just multiply the y velocity by dt

location.add(MOVEMENT * dt, velocity.y * dt, 0);
\$\endgroup\$
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .