Hello,

In previous blog I have discussed about how to load map in libGdx.

Now I am going to discuss about How to detect collision between map and actor.

Step1: Find out cell at xy position is null or not. If cell is solid(not null) then make rectangle

 

 private void getTiles( Array<Rectangle> tiles) {


TiledMapTileLayer layer = (TiledMapTileLayer)WorldRenderer.map.getLayers().getLayer(0);


rectPool.freeAll(tiles); // pool of rectangle.
                           //using pool for optimization.

tiles.clear();
int row= layer.getWidth();
int colum= layer.getHeight();


for(int x= row; x <= row; x++ {
//Systeom.out.println("in y loop.....................");
for(int y = colum; y <= colum; y++) {
com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell cell = layer.getCell(x, y);


if(cell != null  ) {
newCellrect =  rectPool.obtain();
newCellrect.set(x, y, 1f, 1f);
tiles.add(newCellrect);
}}

Step 2: Now place actor in screen then move actor by following code.

// move actor

 if(Gdx.input.isKeyPressed(Keys.LEFT)){

 dx=-1;
 }

if(Gdx.input.isKeyPressed(Keys.RIGHT)){
 dx=1;
}
 if(Gdx.input.isKeyPressed(Keys.DOWN)){
dy=-1;
}

 if(Gdx.input.isKeyPressed(Keys.UP)){

 dy=1;
 }

actor.setXY(actor.getX()+dx,actor.getY()+dy);

Step 3:-

The camera should scroll so that the actor is always in the middle.

Camera.position.x=player.getX();
Camera.position.x=player.getY();

If anyone have Query or problem comment on it.

 

Post By:- Neha Agrawal