Hi. First, sorry if I post this on the wrong place.
I am developing a platform game with slick and JBox2d, but I can’t get the contactlistener (for collision) work. I create a class that implement ContactListener. When the world class is initialized, call the super class and create a map with tiledmap, and look for all the tiles on the map, for create static bodies for collision, but doesn’t work and I can’t see the problem. Any idea? Thanks
Game.class
World world = new World(new Vec2(0, Util.GRAVITY));
world.setContactListener(new Listener(this));
World.class
public class World extends org.jbox2d.dynamics.World {
public World(Vec2 gravity) {
this(gravity, 0);
}
public World(Vec2 gravity, int lvl) {
super(gravity);
try {
map = new TiledMap(Util._RES + path + maps[lvl]);
} catch (SlickException e) {
e.printStackTrace();
}
generateMap();
}
// Generate box2d bodies for all tiles
private void generateMap() {
int layerIndex = map.getLayerIndex("base");
for (int tileX = 0; tileX < map.getWidth(); tileX++) {
for (int tileY = 0; tileY < map.getHeight(); tileY++) {
int tileID = map.getTileId(tileX, tileY, layerIndex);
String type = map.getTileProperty(tileID, "type", null);
if (type != null && type.equals("grass")) {
// Create box2d bodie for this tile
Vector2 position = tileToWorld(tileX, tileY);
position.add(map.getTileWidth() / 2,
map.getTileHeight() / 2);
Vec2 physicsPosition = toPhysicsVector(position);
createBoxBody(physicsPosition, map.getTileWidth(),
map.getTileHeight(), BodyType.STATIC);
}
}
}
}
private Body createBoxBody(Vec2 position, float width, float height,
BodyType type) {
BodyDef bodyDef = new BodyDef();
bodyDef.position = position;
bodyDef.type = type;
bodyDef.linearDamping = 0.5f;
FixtureDef fixture = new FixtureDef();
PolygonShape shape = new PolygonShape();
shape.setAsBox(width * 0.5f / PTM, height * 0.5f / PTM);
fixture.shape = shape;
Body body = createBody(bodyDef);
body.createFixture(fixture);
return body;
}
private Vec2 toPhysicsVector(Vector2 vector) {
return new Vec2(vector.getX() / PTM, vector.getY() / PTM);
}
public Vector2 tileToWorld(int tileX, int tileY) {
return new Vector2(MAP_X + map.getTileWidth() * tileX, MAP_Y
+ map.getTileHeight() * tileY);
}
public Vector2 tiledMapToWorld(float x, float y) {
return new Vector2(MAP_X + x, MAP_Y + y);
}
}
and Listener.class
public class Listener implements ContactListener {
private Game game;
public Listener(Game g) {
this.game = g;
}
@Override
public void beginContact(Contact contact) {
System.out.println("Collision!!");
}
@Override
public void endContact(Contact contact) { }
@Override
public void postSolve(Contact contact, ContactImpulse ci) { }
@Override
public void preSolve(Contact contact, Manifold mani) { }
}
PS: I removed some code for make more redeable the post