My edge collision algorithm is not working properly (java)

时间:2015-04-29 00:29:02

标签: java algorithm collision-detection collision edge

            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 setup a debug that will tell me if which of the 4 Booleans is being set to true, and they don't show that when I put the box 'pl' on top of box 'a' colUP is not equal to true, and they will only come true in weird instances where box 'pl' is colliding with several box 'a's , and the collision for a certain side might be true when it isn't but if colUP is true then colRIGHT is true for some reason. (This code is inside a for loop that goes through an array list of Rectangles and sets the current Rectangle equal to the variable 'a' so that a.x is the box's x position)

1 个答案:

答案 0 :(得分:2)

你有正确的逻辑,但你分别为每个条件设置了false。实际上所有条件都应该是真实的。所以,使用一个布尔变量 - isInRectangle = true;然后检查所有条件 - 左,右,上,下。如果不是,那么isInRectangle = false;

对所有4个条件都是简单的逻辑运算。