Hi,
HINT: before you work through this rather lenghtly post, skip ahead because i solved the problem afterwards (read below)
i'll try to run you through the relevant code parts. I'm using Slick as the game engine, so naturally i have the init(), update() and render() methods where all the interesting code is located. I striped them from code that is not related to Box2D to increase readability.
Code:
public void init(GameContainer container) throws SlickException {
contacts = new ArrayList<ContactPoint>();
// create physics engine
worldAABB = new AABB();
worldAABB.lowerBound = new Vec2(-150.0f, -150.0f);
worldAABB.upperBound = new Vec2(universeDimension.x + 150.0f, universeDimension.y + 150.0f);
Vec2 gravity = new Vec2(0.0f, 0.0f);
boolean doSleep = true;
world = new World(worldAABB, gravity, doSleep);
// i have a second "world" that only holds my camera object. so the camera can "follow" my player
// in a natural looking way, but i don't have to worry about the camera colliding with anything.
// The camera is alone in this "world"
AABB worldAABB1 = new AABB();
worldAABB1.lowerBound = new Vec2(-150.0f, -150.0f);
worldAABB1.upperBound = new Vec2(universeDimension.x + 150.0f, universeDimension.y + 150.0f);
cameraWorld = new World(worldAABB1, gravity, doSleep);
world.setContactListener(this);
spawnPlayer();
addSimulatedObject(new TwinCannon(Game.randomPositionInUniverse()));
addSimulatedObject(new Sentry(new Weapon(300, Integer.MAX_VALUE, 5000, new Ammo(Ammo.STANDARD_VELOCITY,5.0), Weapon.MOUNT_TYPE_SINGLE ), 55.0, 2000, new Vec2( universeDimension.x/2-20, universeDimension.y/2) ));
// define universe boundaries. place some boxes at the boundaries, so the player will
// "bounce" off of them.
Body worldBoundStaticBody = Game.createBodyAt( new Vec2(universeDimension.x / 2, universeDimension.y / 2) );
worldBoundStaticBody.setUserData(this);
PolygonDef westPolDef = new PolygonDef();
westPolDef.setAsBox(50f, universeDimension.y/2 + 100, new Vec2( -universeDimension.x/2-50, 0.0f), 0.0f);
worldBoundStaticBody.createShape(westPolDef);
PolygonDef southPolDef = new PolygonDef();
southPolDef.setAsBox(universeDimension.x/2+100, 50f, new Vec2(0.0f, -universeDimension.y/2-50), 0.0f);
worldBoundStaticBody.createShape(southPolDef);
PolygonDef eastPolDef = new PolygonDef();
eastPolDef.setAsBox(50f, universeDimension.y/2+100, new Vec2(universeDimension.x/2+50, 0.0f), 0.0f);
worldBoundStaticBody.createShape(eastPolDef);
PolygonDef northPolDef = new PolygonDef();
northPolDef.setAsBox(universeDimension.x/2+100, 50f, new Vec2(0.0f, universeDimension.y/2+50), 0.0f);
worldBoundStaticBody.createShape(northPolDef);
// populate camera system
BodyDef camBodyDef = new BodyDef();
camBodyDef.position.set( new Vec2(universeDimension.x/2,universeDimension.y/2) );
camBodyDef.linearDamping = 1.0;
camera = cameraWorld.createBody(camBodyDef);
CircleDef circleDef = new CircleDef();
circleDef.radius = 1.0f;
circleDef.density = 1.0f;
camera.createShape(circleDef);
camera.setMassFromShapes();
// spawn an AI Ship
aiShip = new AIShip();
aiShip.setPosition( new Vec2(universeDimension.x / 2 - 50, universeDimension.y / 2 + 50) );
aiShip.setWaypoint( playerShip.getPosition().clone() );
queueSimulatedObject(aiShip);
}
The update() method:
Code:
public void update(GameContainer container, int delta) throws SlickException {
contacts.clear();
// i'm aware of potential problems with variable timestep, but for now i like to keep it simple
// and it has worked well until now
world.step( (double)delta / 1000.0, iterations );
cameraWorld.step( (double)delta / 1000.0, iterations );
processContacts();
// update all simulated objects
// SimulatedObject is my wrapper or entity class (whatever you may call it) for everything that
// moves around in my game. Most of them also have a box2D body encapsulated
for( SimulatedObject o : simulatedObjects ) {
if (o.isActive() ) {
// this updates stuff like animations and some objects also
// apply torque and force on themselfes, based on user input (turning and
// accelerating the players ship e.g.). But nothing is created or destroyed
// from inside this method. If that would be necessary i would use the
// queueSimulatedObject() and disposeSimulatedObject() construct below, so not to
// break my own for()-loop that i'm in right now.
o.update(timestep);
} else {
disposeSimulatedObject(o);
}
}
// remove disposable objects
for( SimulatedObject o : disposable ) {
simulatedObjects.remove(o);
if (o.getBody() != null) world.destroyBody( o.getBody() );
}
disposable.clear();
// add queued objects. if it's necessary to create new SimulatedObjects this is done here,
// outside of world.step() and my own SimulatedObject.update() loop
for( SimulatedObject o : queuedSimulatedObjects ) {
addSimulatedObject(o);
}
queuedSimulatedObjects.clear();
// let the camera follow the player.
camera.applyForce( new Vec2(-thrust * 400 * Math.sin(lookAt), thrust * 400 * Math.cos(lookAt)), camera.getWorldCenter());
// position window centered on camera position
screenCenterWorld = camera.getPosition();
}
The render() method does not contain any Box2d related code, so i skip this one. here are some helper methods that were referenced from the code above.
The interface for the ContactListener:
Code:
protected ArrayList<ContactPoint> contacts;
public void add(ContactPoint point) {
Object o1 = point.shape1.getBody().getUserData();
Object o2 = point.shape2.getBody().getUserData();
// ignore contacts without userdata
if (o1 == null || o2 == null) return;
//ignore Shot/Shot collisions
if ( o1 instanceof Shot && o2 instanceof Shot) return;
contacts.add(point);
}
public void persist(ContactPoint point) {}
public void remove(ContactPoint point) {}
public void result(ContactResult point) {}
The processing of the Contacts:
Code:
protected void processContacts() {
for(ContactPoint point : contacts) {
Object o1 = point.shape1.getBody().getUserData();
Object o2 = point.shape2.getBody().getUserData();
// remove shots that hit the universe boundaries
if ( (o1 instanceof Shot && o2 instanceof Game) ) {
disposeSimulatedObject((SimulatedObject)o1);
} else if ( (o2 instanceof Shot && o1 instanceof Game) ) {
disposeSimulatedObject((SimulatedObject)o2);
}
// apply damage to anything that is Destructable
if ( o1 instanceof DamagingObject && o2 instanceof Destructable ) {
((Destructable)o2).applyDamage( ((DamagingObject)o1).getDamage() );
if (((DamagingObject)o1).disposesAfterApplyingDamage()) {
disposeSimulatedObject((SimulatedObject)o1);
}
} else if ( o2 instanceof DamagingObject && o1 instanceof Destructable ) {
((Destructable)o1).applyDamage( ((DamagingObject)o2).getDamage() );
if (((DamagingObject)o2).disposesAfterApplyingDamage()) {
disposeSimulatedObject((SimulatedObject)o2);
}
}
}
}
Managing the list of SimulatedObjects.
Code:
public static void addSimulatedObject(SimulatedObject o) {
simulatedObjects.add(o);
}
public static void queueSimulatedObject(SimulatedObject o) {
queuedSimulatedObjects.add(o);
}
public static void disposeSimulatedObject(SimulatedObject o) {
disposable.add(o);
}
And last but not least, to give you an example how a SimulatedObject wrapper-class creates it's underlying Box2D body, here is the constructor of the PlayerShip class (which is the Ship that the player controlls):
Code:
public PlayerShip() {
super();
//create body definition
BodyDef def = new BodyDef();
def.position.set( getPosition() );
def.linearDamping = 1.0;
def.angularDamping = 2.0;
// create the body
body = Game.world.createBody(def);
body.setBullet(true);
// attach the front
PolygonDef polDef1 = new PolygonDef();
polDef1.clearVertices();
polDef1.addVertex( new Vec2(0,3.1) );
polDef1.addVertex( new Vec2(-.3,1.2) );
polDef1.addVertex( new Vec2(.3,1.2) );
polDef1.density = 1.0f;
polDef1.friction = 0.3f;
polDef1.restitution = 0.5f;
body.createShape(polDef1);
//attach the body
PolygonDef polDef2 = new PolygonDef();
polDef2.clearVertices();
polDef2.addVertex( new Vec2(-.3,1.2) );
polDef2.addVertex( new Vec2(-3.6,-2.1) );
polDef2.addVertex( new Vec2(-3.8,-2.9) );
polDef2.addVertex( new Vec2(3.8,-2.9) );
polDef2.addVertex( new Vec2(3.6,-2.1) );
polDef2.addVertex( new Vec2(.3,1.2) );
polDef2.density = 1.0f;
polDef2.friction = 0.3f;
polDef2.restitution = 0.5f;
body.createShape(polDef2);
// update mass properties
body.setMassFromShapes();
body.setUserData(this);
}
As far as i can tell that's all the Box2D related code in my project. If this doesn't help i may send you the code, but it's around 15MB (including resources like graphics), so probably a bit big for email. we'll see.
regards
Max