My collision algorithm is not working as expected (java)

            if(pl.y+pl.height >= a.y && pl.x+pl.width >= a.x+1 && pl.x <= a.x+a.width-1 && pl.y<=a.y) { //TOP
                colUP=true;
            }
            else  colUP=false;

            if(pl.y <= a.y+a.height && pl.x+pl.width >= a.x+1 && pl.x <= a.x+a.width-1 && pl.y+pl.height>=a.y+a.height) { //BOTTOM
                colDOWN=true;
            }
            else colDOWN=false;

            if(pl.x <= a.x+a.width && pl.x+pl.width>a.x+a.width && pl.y+pl.height >= a.y && pl.y <= a.y+a.height){ //RIGHT
                colRIGHT=true;
            }
            else colRIGHT=false;

            if(pl.x+pl.width >= a.x && pl.x<a.x && pl.y+pl.height >= a.y && pl.y <= a.y+a.height){ //LEFT
                colLEFT=true;
            }
            else colLEFT=false;

      

I'm setting up a debug that will tell me if one of the 4 booleans is set to true and they don't show that when I put the "pl" field on top of the "a" field the colUP is not true and they will only be implemented in weird instances where the "pl" field collides with multiple "a" fields and the collision for a particular side may be true if it is not, but if colUP is true then COLORIGHT is true for some reason. (This code is inside a for loop that loops through the list of Rectangles and sets the current Rectangle to 'a' so that ax is the x field of position)

+3


source to share


1 answer


You have the correct logic, but you are setting false for each condition separately. In reality, all conditions must be true. So, use one boolean variable - isInRectangle = true; then check all conditions: left, right, top, bottom. If any value is not true, then isInRectangle = false;



This is a simple and logical operation for all 4 conditions.

+2


source







All Articles