How to properly check where a tile is on a tiled implementation in libgdx

  Kiến thức lập trình

I am using libgdx to create a super mario clone and I have created a tilemap in tiled. I have not used libgdx before so I am not very sure how it all works, but when I added the tilemap to my screen the tilemap was super small so I zoomed the camera. I wrote a script to get the screen coordinates and check them against the tile coordinates to see if my mouse is hovering over a tile, but the outlined tile is offset to the right by a bunch and is up too much. I don’t really know how to proceed from here and other resources online have not helped. Any ideas would be greatly appriciated!

    public void create() {
        map = new TmxMapLoader().load("1-1.tmx");

        camera = new OrthographicCamera();
        camera.setToOrtho(false, Gdx.graphics.getWidth() * 2, Gdx.graphics.getHeight() * 2);
        camera.position.set(220, 138, 0);
        camera.zoom = 0.129f;

        renderer = new OrthogonalTiledMapRenderer(map);
    private void debugTileUnderMouse(float worldX, float worldY, int tileX, int tileY, int tileWidth, int tileHeight) {
        ShapeRenderer shapeRenderer = new ShapeRenderer();
        shapeRenderer.setProjectionMatrix(camera.combined);
        shapeRenderer.begin(ShapeRenderer.ShapeType.Line);

        shapeRenderer.setColor(0, 1, 0, 1);
        shapeRenderer.rect(tileX * tileWidth, tileY * tileHeight, tileWidth, tileHeight);

        shapeRenderer.setColor(1, 0, 0, 1);
        shapeRenderer.circle(worldX, worldY, 5);

        shapeRenderer.end();
        shapeRenderer.dispose();
    }

    private void checkTileUnderMouse() {
        Vector3 mousePos = new Vector3(Gdx.input.getX(), Gdx.input.getY(), 0);
        Vector3 worldPos = camera.unproject(mousePos);

        int tileWidth = map.getProperties().get("tilewidth", Integer.class);
        int tileHeight = map.getProperties().get("tileheight", Integer.class);


        int tileX = (int) (worldPos.x / tileWidth);
        int tileY = (int) (worldPos.y / tileHeight);

        TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(0);
        TiledMapTileLayer.Cell cell = layer.getCell(tileX, tileY);

        if (cell != null) {
            TiledMapTile tile = cell.getTile();
            if (tile != null) {
                System.out.println("Mouse is over tile at (" + tileX + ", " + tileY + "), Tile ID: " + tile.getId());
            }
        }
        debugTileUnderMouse(worldPos.x, worldPos.y, tileX, tileY, tileWidth, tileHeight);
    }

The tile is offset and 3 to the right

The hovered tile is offset and 3 to the right

let me know if there is anything else I can provide to help

LEAVE A COMMENT