I’m really struggling with collision detection. I started with a pretty simple way to test collision using LibGDX’s rectangles and the overlap method to test if the rectangle of the player overlaps with a rectangle of a mob. That worked pretty fine until i realized that it doesn’t work fine.
http://imageshack.com/a/img842/5804/if5g.png
This is as near as I can get to him, which is pretty much what I want. But if I approach another mob:
http://imageshack.com/a/img823/9654/hhnd.png
The difference is not really easy to see if you don’t now what you’re looking for, but as soon as I only render the collisionboxes the difference between these two is a bit more obvious:
http://imageshack.com/a/img840/8097/qrs.png
http://imageshack.com/a/img822/606/sgxo.png
I first tried to keep the code for detecting collision as simple as possible by only using
public boolean collision(CollisionBox colBox){
return colRect.overlaps(colBox.colRect);
}
Just if in case you are wondering: a CollisionBox contains a Rectangle (“colRect”) and an Entity. This method is called everytime a mob is moving on the map.
As soon as I realized that there is this little problem I tried other ways to test the collision, for example the Intersector:
public boolean collision(CollisionBox colBox){
return Intersector.overlaps(colRect, colBox.colRect);
}
Another way was testing if the corners of the collision-Rectangle are inside the other collision-Rectangle:
public boolean collision(CollisionBox colBox){
for(int i = 0; i < 4; i++){
float xCorner = colRect.x + ((i / 2) * colRect.width);
float yCorner = colRect.y + ((i % 2) * colRect.height);
if(xCorner >= colBox.colRect.x && yCorner >= colBox.colRect.y && xCorner <= (colBox.colRect.x + colBox.colRect.width) && yCorner <= (colBox.colRect.y + colBox.colRect.height)){
return true;
}
}
return false;
}
My last attempt on this was something I found here: http://www.java-gaming.org/index.php?topic=29567.0
public boolean collision(CollisionBox colBox){
double x1 = colRect.x;
double y1 = colRect.y;
double w1 = colRect.width;
double h1 = colRect.height;
double x2 = colBox.colRect.x;
double y2 = colBox.colRect.y;
double w2 = colBox.colRect.width;
double h2 = colBox.colRect.height;
double cntrX1 = x1 + w1 / 2;
double cntrY1 = y1 + h1 / 2;
double cntrX2 = x2 + w2 / 2;
double cntrY2 = y2 + h2 / 2;
double distanceX = Math.abs(cntrX1 - cntrX2);
double distanceY = Math.abs(cntrY1 - cntrY2);
double sumWidth = (w1 / 2 + w2 / 2);
double sumHeight = (h1 / 2 + h2 / 2);
if (distanceX < sumWidth && distanceY < sumHeight) {
return true;
}
return false;
}
But still, each of these attempts failed to remove this inaccuracy. Is there anything im doing wrong or anything I could do better to make it work perfectly?