Sunday, June 22, 2014

[libgdx] day 10 – tilemaps

To create tilemaps we first need to install the Tiled Map Editor: http://www.mapeditor.org/
(when you have linux you may have to compile it yourself. everything you need to know is in the README file)
After we start the program, we create a new map via File > New. Here we have to specify the size of the map and the size of the tiles.
Now we need tiles, that our map consists of. I downloaded this tileset and put it into a new subfolder maps of my stuff folder.

In Tiled we now click Map > New Tileset and select our tilesetfile to be the tileset.

In the right collumn we can see the layers and the tiles.
We create a layer for objects and one layer for the ground and then create a nice little map. To draw a tile, just select the layer and the tile and then click into the left part of the screen on the fitting place.
Then we save our map as a .tmx file into the stuff/maps folder where our tileset-Image is.
As for textures there is a map-packer in libgdx:
java -classpath [path tol ibgdx]/gdx.jar:[path to libgdx]/extensions/gdx-tools.jar:[path to libgdx]/extensions/gdx-tiled-preprocessor.jar com.badlogic.gdx.tiledmappacker.TiledMapPacker [path to stuff]/maps [path to testgame-android]/assets/maps 
If the map is packed in our assets-folder, it’s really easy to draw it:
TiledMap map;
TileAtlas atlas;
TileMapRenderer tileMapRenderer;
OrthographicCamera camera;
public IngameScreen(){
 // load tilemap
 map = TiledLoader.createMap(Gdx.files.internal("maps/testmap.tmx"));
 atlas = new TileAtlas(map, Gdx.files.internal("maps"));
 tileMapRenderer = new TileMapRenderer(map, atlas, 8, 8); // handles rendering the tile map. 8x8 is the chunk size to preload
 camera=new OrthographicCamera(800,480);
}

@Override
public void render(float delta) {
 Gdx.gl.glClearColor(1,1,1, 1);

 // move map
 if(Gdx.input.isKeyPressed(Keys.LEFT)){
  camera.position.x=camera.position.x-Gdx.graphics.getDeltaTime()*300;
 }
 if(Gdx.input.isKeyPressed(Keys.RIGHT)){
  camera.position.x=camera.position.x+Gdx.graphics.getDeltaTime()*300;
 }
 if(Gdx.input.isKeyPressed(Keys.DOWN)){
  camera.position.y=camera.position.y-Gdx.graphics.getDeltaTime()*300;
 }
 if(Gdx.input.isKeyPressed(Keys.UP)){
  camera.position.y=camera.position.y+Gdx.graphics.getDeltaTime()*300;
 }
 if(Gdx.input.isKeyPressed(Keys.PLUS)){
  camera.zoom-=Gdx.graphics.getDeltaTime();
 }
 if(Gdx.input.isKeyPressed(Keys.MINUS)){
  camera.zoom+=Gdx.graphics.getDeltaTime();
 }  
 camera.update();

 Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
 // render map
 tileMapRenderer.render(camera); 
}

Seems pretty easy to me. If you though got problems, write a comment.

No comments:

Post a Comment

Popular Posts