1
votes

Below is my code that detects collision between two objects, setting a boolean to true every time my player collides with the wall:

private boolean collide(){
    for(int i = 0; i < handler.object.size(); i++){
        if(this.getBounds().intersects(handler.object.get(i).getBounds()) && handler.object.get(i).getId() != ID.Player && handler.object.get(i).getId().equals(ID.Wall)){
            System.out.println("COLLIDEEEEE");
            return true;
        }
    }
    return false;
}

My intent is to have the player stop moving upon collision. Right now my Code for the player Movement looks like this:

public void tick() {
    if (Var.A == true && Var.ableToMove == true) {
        Var.OffsetX += Var.speed;

    }
    if (Var.D == true && Var.ableToMove == true) {
        Var.OffsetX -= Var.speed;

    }

What i now want to do is, I want the player stop upon colliding the wall. I would really appreciate if anyone of you could help me.

1
two* objects :D - Maxi Keller
What kind of help do you asking for? Your collide() method seems to work fine. - Sergey
What do you mean by the player stopping? What would that actually entail? - yshavit
My answer now is how i can make the Player object stop moving through the Wall. So he cant pass the wall. - Maxi Keller
@MaxiKeller then maybe you should tell us more about Player ant it's moving - Sergey

1 Answers

1
votes
if(this.getBounds().intersects(handler.object.get(i).getBounds()) 

seems fine to detect collision between this (the player) and other elements.

but this doesn't seem fine :

handler.object.get(i).getId() != ID.Player && handler.object.get(i).getId().equals(ID.Wall)){

1) It is not consistent.
The first comparison compares the reference of the id objects :

handler.object.get(i).getId() != ID.Player 

The second one compares the id objects according to the equals() method :

handler.object.get(i).getId().equals(ID.Wall))

You should use the same way in both cases. You don't specify if you use String for id but Strings should be compared with equals() as a general way.

2)You should not need to make two comparisons.

Assuming that ID.Player and ID.Wall are two distinct values, if handler.object.get(i).getId().equals(ID.Player) is true, it means that handler.object.get(i).getId().equals(ID.Wall) is false.

handler.object.get(i).getId().equals(ID.Wall) should be enough.