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);
}