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
\$\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\$
  • \$\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\$ – Giuseppe Romeo Sep 4 '17 at 10:07

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.