I am creating a RPG game using the Libgdx library and I am having difficulty with setting up the rectangles for the collision detection. I was able to draw a rectangle around my main character and I know the code for how to handle the collision when it happens. The problem is that I need to draw rectangles around the tiles in my collision layer(my collision layer is not a object layer). If anyone is able to give an example of how to write this or even point me in the right direction, this would be very helpfull.
tile size is 32x32
here is the code that I have come up with so far for drawing the rectangles around the specified tiles
public void collisionSetUp(){
TiledMapTileLayer layer;
layer = (TiledMapTileLayer) map.getLayers().get("Bushes");
float tileWidth = layer.getTileWidth(); //the tile is a perfect square so only one side is required
//go through the entire layer and assign a rectangle to each tile
for(int row = 0; row < layer.getHeight(); row++) {
for(int col = 0; col < layer.getWidth(); col++) {
debugRenderer.begin(ShapeType.Line);
collisonRect = new Rectangle(row*32, col*32, 32, 32);
debugRenderer.setColor(new Color(0, 1, 0, 1));
debugRenderer.rect(collisonRect.getX(), collisonRect.getY(), collisonRect.width, collisonRect.height);
debugRenderer.end();
System.out.println("new Rectangle");
}
}
}
code for handling the collision
Rectangle playerRect = new Rectangle(player.position.x, player.position.y, 32, 32);
debugRenderer.setColor(new Color(0, 1, 0, 1));
debugRenderer.rect(player.position.x, player.position.y, playerRect.width, playerRect.height);
debugRenderer.end();
if(playerRect.overlaps(collisonRect)){
player.position.x = player.prePosition.x;
player.position.y = player.prePosition.y;
}