0
\$\begingroup\$

I'm making a top-down tiled game in Java, and now I'm coding the collision test, but it doesn't work. This collision function work only for top and left side of the blocks, and when I'm colliding, the player moves up without I do anything.

What is my mistake?There are better collision system? Thank you!

My code:

  public void update() {
        collide();

        if(up) y -= vely;
        if(down) y += vely;
        if(right) x += velx;
        if(left) x -= velx;
    }

    private void collide(){
        for(int i = 0; i < handler.objects.size(); i++){
            GameObject obj = handler.objects.get(i);
            if(obj.id() == ID.Block){
                if(getBounds().intersects(obj.getBounds())){
                    x += -velx;
                    y += -vely;
                }
            }
        }
    }

// is the same in all the classes
public Rectangle getBounds() {
    return new Rectangle((int)x,(int)y,width,height);
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Your current implementation moves the player up and left whenever it collides with the block. Instead move it relative to it's velocity:

private void collide(){
    for(int i = 0; i < handler.objects.size(); i++){
        GameObject obj = handler.objects.get(i);
        if(obj.id() == ID.Block){
            if(getBounds().intersects(obj.getBounds())){
                if (right) x -= velx;
                if (left) x += velx;
                if (up) y += vely;
                if (down) y -= vely;
            }
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ there are 2 problems: sometimes when the player collides with a block, he can't anymore moves, and other times when the player collide with a block, he can only moves in the space inside it \$\endgroup\$ Sep 4, 2017 at 10:07

You must log in to answer this question.

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