3
\$\begingroup\$

My player is getting caught on something on the floor. My whole environment is just blocks. I have looked through (and tried to change) just about everything I can think of in my player update method. Any idea what could be solving this? Here is the code:

public void update(GameContainer gc, int delta, Map m){
    boolean updateX = true;
    boolean updateY = true;

    if(!movingLeft && dx < 0f){
        dx += .2f;
    }
    if(!movingRight && dx > 0f){
        dx -= .2f;
    }

    if(!movingLeft && !movingRight && ((dx < 0 && dx > -.2f) || (dx > 0 && dx < .2f))){
        dx = 0f;
    }
    boolean fallFlag = true;
    prx = new Rectangle(x + dx, y, 10, 10);
    pry = new Rectangle(x, y + dy, 10, 10);
    for(Platform p : m.platforms){
        r = new Rectangle(p.getX() - 2, p.getY() - 2, 20 + 2, 20 + 2);
        if(prx.intersects(r)){
            updateX = false;
            dx = 0;
        }
        //check if my dy will cause me to hit a platform
        if(pry.intersects(r)){
            //if I am moving down, set falling to false
            if(dy > 0)
                fallFlag = false;
            updateY = false;
            dy = .025f;
        }
    }
    inAir = fallFlag;
    if(inAir)
        dy += .025f;
    if(updateX)
        x+=dx*(delta/10);
    if(updateY)
        y+=dy*(delta/10);
}
\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

I think the problem is that you are not taking gravity into consideration when checking for collision. For example, you update dy as follows:

if(inAir)
    dy += .025f;

However, for your collision check rectangle, you do the following:

pry = new Rectangle(x, y + dy, 10, 10);

This takes into account the movement of your object based on input, but it doesn't take into account the extra 0.025f accumulated by your falling acceleration.

Instead, create your rectangle as follows, and it may fix your issue:

if (inAir)
   pry = new Rectangle(x, y + dy + 0.025f, 10, 10);
else 
   pry = new Rectangle(x, y + dy, 10, 10);
\$\endgroup\$
3
  • \$\begingroup\$ Awesome. Glad I was right :) \$\endgroup\$
    – jgallant
    Commented May 23, 2013 at 16:06
  • \$\begingroup\$ I got 15 reputation and upvoted you! :) \$\endgroup\$
    – Brandon
    Commented May 23, 2013 at 18:35
  • \$\begingroup\$ @Brandon Welcome to the community. \$\endgroup\$
    – jgallant
    Commented May 23, 2013 at 19:32

You must log in to answer this question.

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