I've been trying to program a game for the past while and I can't ever figure out one thing: collision detection. I can get up+down and left+right to work, but when I put them together, they interfere with each other.
I seriously don't really know how to do it, and I don't want to have to use Box2D or any other premade collision detection system. All I need is something simple and will work in 4 directions.
Here's the code I have now from my Player class:
for (int i = 0; i < blocks.size(); i++) {
Block b = blocks.get(i);
if (isCollidingDown(b)) {
b.doTopCollision(this);
}
else if (isCollidingUp(b)) {
b.doBottomCollision(this);
}
else if (isCollidingLeft(b)) {
b.doRightCollision(this);
}
else if (isCollidingRight(b)) {
b.doLeftCollision(this);
}
}
Here's the actual detection code. I know it's long, but just roll with it:
public boolean isCollidingDown(Block b) {
if ((Float.compare(this.yPos,b.yPos+b.height) <= 0) && (Float.compare(this.yPos,b.yPos)>=0) && (Float.compare(this.yPos+this.height,b.yPos+b.height)>=0)) {
if (((Float.compare(this.xPos, b.xPos)>=0) && (Float.compare(this.xPos, b.xPos+b.width)<= 0)) ||
((Float.compare(this.xPos+this.width,b.xPos)>=0) && (Float.compare(this.xPos+this.width,b.xPos+b.width)<=0))) {
return true;
}
}
return false;
}
public boolean isCollidingUp(Block b) {
if ((Float.compare(this.yPos+this.height,b.yPos) >=0) && (Float.compare(this.yPos+this.height,b.yPos+b.height)<=0) && (Float.compare(this.yPos,b.yPos)<=0)) {
if (((Float.compare(this.xPos, b.xPos)>=0) && (Float.compare(this.xPos, b.xPos+b.width)<= 0)) ||
((Float.compare(this.xPos+this.width,b.xPos)>=0) && (Float.compare(this.xPos+this.width,b.xPos+b.width)<=0))) {
return true;
}
}
return false;
}
public boolean isCollidingLeft(Block b) {
if ((Float.compare(this.xPos,b.xPos+b.width) <=0) && (Float.compare(this.xPos,b.xPos)>=0)) {
if (((Float.compare(this.yPos, b.yPos)>=0) && (Float.compare(this.yPos, b.yPos+b.height)<=0)) ||
((Float.compare(this.yPos+this.height,b.yPos)>=0) && (Float.compare(this.yPos+this.height,b.yPos+b.height)<=0))) {
return true;
}
}
return false;
}
public boolean isCollidingRight(Block b) {
if ((Float.compare(this.xPos+this.width,b.xPos) >=0) && (Float.compare(this.xPos+this.width,b.xPos+b.width)<=0)) {
if (((Float.compare(this.yPos, b.yPos)>=0) && (Float.compare(this.yPos, b.yPos+b.height)<= 0)) ||
((Float.compare(this.yPos+this.height,b.yPos)>=0) && (Float.compare(this.yPos+this.height,b.yPos+b.height)<=0))) {
return true;
}
}
return false;
}
Note that I had to do this Float.compare() thing because floats aren't accurate when comparing. Also, I'm not using Java2D, I'm using a framework called libgdx. That shouldn't matter though.
What can I do? Thanks!
EDIT: Guys, that's not the point. I know my code is very unprofessional, but the point is that the collisions don't work the way they're supposed to. I just need a 4-way collision system with boxes. That's all.