Search code examples
javalibgdxtmx

Collision Detection Tmx Maps using libgdx (java)


So I'm trying to implement collision detection in my game and I have a layer in the tmx file called Collision. The LIBGDX onsite tutorials doesnt cover interaction with object layers and it was hard to figure out how to render the map in the first place. This is how I render my screen, I would like to learn how to get my collision layer and then get my sprite to interact with it.

@Override
    public void render(float delta) {
        translateCamera();

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        camera.update();

        renderer.setView(camera);

        renderer.render(bgLayers);
        // renderer.render();

        batch.begin();

        batch.draw(playerDirect, Gdx.graphics.getWidth() / 2,
                Gdx.graphics.getHeight() / 2);

        batch.end();
        renderer.render(fgLayers);

    }

Solution

  • I'd reccomend adding blocked properties to the actual tiles themselves - you can add tile properties via the Tiled editor on the actual tileset. You can retrieve their properties on the tileset. I'm going to quote the documentation:

    A TiledMap contains one or more TiledMapTileSet instances. A tile set contains a number of TiledMapTile instances. There are multiple implementations of tiles, e.g. static tiles, animated tiles etc. You can also create your own implementation for special

    Cells in a tile layer reference these tiles. Cells within a layer can reference tiles of multiple tile sets. It is however recommended to stick to a single tile set per layer to reduce texture switches.

    Specifically, call getProperties on the tile in a tileset. This will retrieve the propeties - then you can compare to your custom attribute and this can tell you if a particular tile is blocked - then you can go ahead and implement your own collision logic.