Reputation: 1
I've been trying to find/create a collision detection for rectangles in Libgdx but I can't seem to get anywhere. I have a rectangle called bucket with width and height 64 and a rectangle called wall with width and height 64. I'm trying to make it so that the player does not pass through the rectangle and can continue on moving while sticking to the wall without phasing through or random teleporting. My method works when there is 1 block but when there is more then one it just breaks and doesn't work.
I know this method is ugly but it is just experimentation
private void checkCollisions(Rectangle bucket, Wall wall){
if(bucket.overlaps(wall.getRectangle())){
if(bucket.x > wall.getRectangle().x - 64 && bucket.x < wall.getRectangle().x - 55){
//collision with right side
bucket.x = wall.getRectangle().x - 64;
}
if(bucket.x < wall.getRectangle().x + 64 && bucket.x > wall.getRectangle().x + 55){
//collision with left side
bucket.x = wall.getRectangle().y + 64;
}
if(bucket.y < wall.getRectangle().y + 64 && bucket.y > wall.getRectangle().y + 55){
//collision with top side
bucket.y = wall.getRectangle().y + 64;
}
if(bucket.y > wall.getRectangle().y - 64 && bucket.y < wall.getRectangle().y - 55){
//collision with bottom side
bucket.y = wall.getRectangle().y - 64;
}
}
}
I would be very appreciative if someone could point me in the correct direction or share some code that would help me.
Upvotes: 0
Views: 740
Reputation: 1974
In LibGDX
when looking at collision detection you must first note two important aspects of the default LibGDX Coordinate system.
Using this information we can fix your logic for collisions to the following:
private void checkCollisions(Rectangle bucket, Wall wall){
if(bucket.overlaps(wall.getRectangle())){
if(bucket.x + 64 > wall.getRectangle().x && bucket.x < wall.getRectangle().x){
//collision with right side of bucket
}
if(bucket.x < wall.getRectangle().x + 64 && bucket.x > wall.getRectangle().x){
//collision with left side of bucket
}
if(bucket.y + 64 > wall.getRectangle().y && bucket.y < wall.getRectangle().y){
//collision with top side of bucket
}
if(bucket.y < wall.getRectangle().y + 64 && bucket.y > wall.getRectangle().y){
//collision with bottom side of bucket
}
}
}
This method will determine which side of the bucket detected a collision with the default LibGDX coordinate system.
Upvotes: 1