Mertcan Ekiz
Mertcan Ekiz

Reputation: 711

Platformer collision (penetrates to ground a few pixels)

I'm trying to make a platform game. I have the collision code (almost) but there seems to be a bug. I try this code:

 for (int i = 0; i < world.ground.size(); i++) {
        if (!world.ground.get(i).intersects((int) x, (int) y, player_width, player_height + (int) dy)) {
            y += dy;
            if (dy < 4) {
                dy += 0.1;
            }
        } else {
            dy = 0;
            jumped = false;
        }
    }

But sometimes my character's foot goes through the ground by 2 or 3 pixels. Is there a better way to do this? Please help, thanks.

Upvotes: 3

Views: 524

Answers (1)

huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11926

It seems like you are using a posteriori (discrete) collision detection. This causes your object penetrate through a little every time becuse it activates only when touched or penetrated. You may think to convert this to a priori (continuous) collision detection. This way, it never penetrates the ground because it checks before the collision then adjusts speed or position in order to avoid penetration.

If you dont want to fiddle with this kind, you can just add a correction function that acts before painting.

void foo()
{
      //check if below ground
      //if yes, displecement upwards until it is above enough
      //now you can paint
      //return
}

I see you implemented this:

  what_you_need_to_make_it_above_ground=(ground_y-feet_y);


  //im not sure if dy is ground level so i added second boolean compare

  if ((dy < 4)||(ground_y>feet_y)) {
                 dy += 0.1; // this isnt enough. should be equal to:
                 dy +=what_you_need_to_make_it_above_ground;
                 dy +=if_there_are_other_parameters_think_of_them_too;

              }

Upvotes: 3

Related Questions