Search code examples
javaandroidlibgdx2d-games

Accessing A Specific Cell's Tile In LibGDX


I have started to create a 2D game in LibGDX using a map(32x32 8 pixel tiles) from tiled map editor. In the method generateMushrooms, I want to access the cell(1,2) in layer 1 and set its tile to another tile in my tileset sprites.png with the id of 8. How would I achieve this? Right now I am getting a null pointer exception.

   
public void create() {

float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera();
camera.setToOrtho(false, 256, 256);
camera.update();
tiledMap = new TmxMapLoader().load("custom.tmx");
tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap);
generateMushrooms();
Gdx.input.setInputProcessor(this);
sb = new SpriteBatch();
texture = new Texture(Gdx.files.internal("badlogic.jpg"));
sprite = new Sprite(texture, 50, 50);
}

@Override
public void render() {

Gdx.gl.glClearColor(0, 0, 0, 0);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
camera.update();

tiledMapRenderer.setView(camera);
tiledMapRenderer.render();
sb.setProjectionMatrix(camera.combined);
sb.begin();
//sprite.draw(sb);
sb.end();
}


public void generateMushrooms() {

//Get first layer

TiledMapTileLayer layer = (TiledMapTileLayer) tiledMap.getLayers().get(1);

// Get cell at row 1 column 2

TiledMapTileLayer.Cell cell = layer.getCell(1, 2);

// Get Tileset

TiledMapTileSet tileSet = tiledMap.getTileSets().getTileSet("sprites.png");

//Set tile of id 8 for the cell

cell.setTile(tileSet.getTile(8));

//Set the cell back in the layer at their x and y positions

layer.setCell(8, 16, cell);

}


Solution

  • Solved my problem! I have a traversing for loop go through the tiles and replace certain tiles like this (note that cur is a layer in the map).

    for(int i=0; i < row; i++)
    {
        for(int j=0; j < column; j++)
        {
            cell = cur.getCell(i, j);
            cur.setCell(i * 8, j * 8, cell);
            cell.setTile(new StaticTiledMapTile("Some type of TextureRegion/Texture");
        }
    }