Search code examples
javalibgdxbox2dtiled

How can I get the location of a tile from a cell in libGDX using floats?


I am currently making a game. It is a 2D tile based game. I tried to make it so that when you step on water your players speed and size changes.

I am running this every 60th of a second:

if(map.getTileTypeByCoordinate(0, player.sprite.getX()/4.0f, player.sprite.getY()/4.0f) == TileType.WATER){
    player.sprite.setScale(2, 1.75f);
    player.speed = 3;
} else {
    player.sprite.setScale(2, 2);
    player.speed = 5;
}

The map.getTileTypeByCoordinate(int layer, float x, float y); method is the following:

public TileType getTileTypeByCoordinate(int layer, float col, float row) {
    Cell cell = ((TiledMapTileLayer) tiledMap.getLayers().get(layer)).getCell((int)(col), (int)(row));

    if(cell != null){
        TiledMapTile tile = cell.getTile();

        if(tile != null){
            int id = tile.getId();
            return TileType.getTileTypeById(id);
        }
    }

    return TileType.GRASS;
}

If I don't cast col and row to integers, then I get an error, obviously.

The reason this is a problem is because I am using Box2D to check collisions. I divide everything by my scale (10.0f) so that the physics simulations are more accurate and I can make the player move faster.

I was wondering if there is a way to get a tile from a float location instead of an int location. Will I have to stop using Box2D for collision detection? I am fine with this, but I am not any good with programming my own collision detection, so if this is the case, how would I go about making my own?


Solution

  • If you are using a scale to use Box2D then you'll need to scale your coordinates back up.

    If you're sprite is at pixel 100 then it's box2d coordinate is 10m. Tiled wants coordinates in pixels so just multiply by your scale.

    player.sprite.getX() * scale

    Of course there might be some casting with the scale.

    Hope this helped and comment if you've any further questions!