How to do collision detection between player and rectangular map object layer?

by satya   Last Updated August 02, 2018 11:13 AM

I am developing a 2d platformer game where i have implemented tile map using tiled editor.I want to collide the player with the ground.I have determined the coordinates for the platform and for the player.How can i achieve collision detection?Here is the code

``````private void createTiles() {
try {

} catch (Exception e) {
System.out.println("Cannot find file: maps//tilemap_" + level + ".tmx");
Gdx.app.exit();
}
//orthomap = new OrthogonalTiledMapRenderer(tileMap,1);

// tileSize=(int)tileMap.getProperties().get("tilewidth", Integer.class);
System.out.println("Tile Size " + tileSize);
tileMapWidth = Integer.parseInt(tileMap.getProperties().get("width").toString());
tileMapHeight = Integer.parseInt(tileMap.getProperties().get("height").toString());
tileSize = Integer.parseInt(tileMap.getProperties().get("tilewidth").toString());
TiledMapTileLayer layer;

for (MapObject object : tileMap.getLayers().get("Blue").getObjects()) {

BodyDef bdef = new BodyDef();
FixtureDef fdef = new FixtureDef();
Body body;
Shape shape;
if (object instanceof RectangleMapObject) {
shape = getRectangle((RectangleMapObject) object);

}
else {
continue;
}
float rectx=  ((RectangleMapObject) object).getRectangle().x;
float recty=      ((RectangleMapObject) object).getRectangle().y;
System.out.println("Rectangle x"+rectx/tileSize+"Rectangle y"+recty/tileSize);
System.out.println("Player position x"+player.getPosition().x+"Player position y"+player.getPosition().y);
CollisionDetection(rectx,recty,player.getBody().getPosition().x*tileSize,player.getBody().getPosition().y*tileSize);
bdef.type = BodyDef.BodyType.StaticBody;
body = world.createBody(bdef);
fdef.shape = shape;
fdef.isSensor=true;
fdef.friction=0;

body.createFixture(fdef);
}
}

private static PolygonShape getRectangle(RectangleMapObject rectangleObject) {
Rectangle rectangle = rectangleObject.getRectangle();
PolygonShape polygon = new PolygonShape();
Vector2 size = new Vector2((rectangle.x + rectangle.width * 0.5f) / PPM,
(rectangle.y + rectangle.height * 0.5f ) /PPM);
polygon.setAsBox(rectangle.width * 0.5f /PPM,
rectangle.height * 0.5f / PPM,
size,
0.0f);
return polygon;
}

public void CollisionDetection(float rectx,float recty,float x,float y){
if(x>= rectx && y>=recty){
collision_yes =true;
if(rectx ==x && recty ==y)
player.setPosition((int)rectx,(int)recty);
player.getBody().setLinearVelocity(player.getBody().getLinearVelocity().x, 0);
player.getBody().applyForceToCenter(0, 150, true);;

}
}
``````
Tags :