sorry for the badly worded question, I'm not exactly sure how to ask this. I'm making a small game with LibGDX and I'm having trouble with collisions.
Basically, my original idea was to simply check whether or not the terrain rectangle and the player rectangle overlapped each other, and if they did, I would move the player rectangle so that it wouldn't overlap the terrain. However, I did this and it wasn't working how I had expected, and it was basically thinking that the top and bottom of the player rectangle were also colliding with the side of the terrain, and then it slides the rectangle along the terrain.
So, I was recommended to try to make a sort of box cast and honestly it hasn't really been working either. I'm new to libgdx so I'm not sure if there's an easier way to do this or not but I've tried looking around. Here's my code:
void handleCollisions() {
Rectangle pRect = player.getRect();
for(Rectangle mapRect : mapRects) { //mapRect is the terrain rectangle
//if(mapRect.overlaps(pRect)) {
float amountCollidedTop = 0f;
float amountCollidedBottom = 0f;
float amountCollidedLeft = 0f;
float amountCollidedRight = 0f;
float xCollided = 0;
float yCollided = 0;
if(mapRect.overlaps(player.boxCastTop)) {
}
if(mapRect.overlaps(player.boxCastRight)) {
xCollided = player.boxCastRight.x + player.boxCastRight.width - mapRect.x;
if(mapRect.y > player.boxCastRight.y) {
yCollided = mapRect.height-(mapRect.y - player.boxCastRight.y);
} else {
yCollided = mapRect.height-(player.boxCastRight.y-mapRect.y);
}
//what percentage of the box cast is being collided with?
amountCollidedRight = (xCollided*yCollided)/player.boxCastRight.area();
System.out.println(amountCollidedRight);
}
//}
}
}
Here's what the collision looks like
Here is what is appearing in the console
Maybe this isn't the way to go with collisions? If it isn't, is there another way that works better? If anyone needs anything clarified please let me know. Thanks!
You should have a look at the libGDX Demo Projects for reference.
Especially libgdx-demo-cuboc could be interesting for you, since it is a platformer with a simple collision system (most of it is implemented in the class Bob I think).
Or if you want to use Box2D (a 2D physics library that many libGDX projects make use of) you can have a look at the libgdx-demo-vector-pinball project.