0
votes

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);

}
1
where is your null pointer exception ?Abhishek Aryan
Layers start at 0 are you getting the correct layer?dfour
The null pointer exception is at the line cell.setTile(tileSet.getTile(8)); Layer 0 holds my background tiles and I was hoping to draw a tile in layer 1 which should be above the background. There is also no tile at that cell and I am trying to set the tile of the cellretchers

1 Answers

0
votes

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");
    }
}