I'm doing something wrong when trying to get bodies to collide using jBox2d & Slick2d. Here is have just my basic init, update, and render methods. Render and update seem to work fine for drawing (gravity effectively pushes the ball down, and will rotate if I apply an impulse).
I have a feeling I'm overlooking something when creating the edge, but I have no idea what. My shapes/bodies work fine in the testbed, but I'm having no luck in my standalone application. I have experimented with moving the edge body / ball body around, but it doesn't seem to have any effect.
@Override
public void init(GameContainer gc, StateBasedGame sbg)
throws SlickException {
world = new World(new Vec2(0F, 9.8F), false);
windowCenter = new Vec2(gc.getWidth() / 2, gc.getHeight() / 2);
circleShape.m_radius = CONSTANTS.BALL_RADIUS * CONSTANTS.SCALE_FACTOR;
circleFixtureDef.shape = circleShape;
circleFixtureDef.density = 1f;
circleFixtureDef.restitution = .6f;
circleBodyDef.type = BodyType.DYNAMIC;
circleBodyDef.bullet = true;
circleBodyDef.position.set(windowCenter);
circleBody = world.createBody(circleBodyDef);
circleBody.createFixture(circleFixtureDef);
bottomEdge.setAsEdge(new Vec2(0, gc.getHeight()), new Vec2(gc.getWidth(), gc.getHeight()));
bottomEdgeDef.position.set(0f, gc.getHeight());
bottomEdgeDef.type = BodyType.STATIC;
bottomEdgeFixtureDef.restitution = .6f;
bottomEdgeFixtureDef.density = 0f;
bottomEdgeBody = world.createBody(bottomEdgeDef);
//bottomEdgeBody.createFixture(bottomEdgeFixtureDef);
ball = new Image("src/main/resources/bball.png");
float shapeToImageFactor = ball.getWidth() / circleShape.m_radius;
ball = ball.getScaledCopy(1 / shapeToImageFactor);
circleBody.setUserData(ball);
}
@Override
public void render(GameContainer gc, StateBasedGame sbh, Graphics g)
throws SlickException {
Vec2 ballBodyPos = circleBody.getPosition();
ball.draw(ballBodyPos.x, ballBodyPos.y);
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException {
world.step(delta, 10, 10);
ball.setRotation((float)Math.toDegrees(circleBody.getAngle()));
System.out.println(world.getBodyCount());
if (world.getContactCount() > 0) {
System.out.println("thank god, something hit another thing");
}
}
Also, the commented out bottomEdgeBody.createFixture(bottomeEdgeFixtureDef) throws a NullPointerException, and I have no idea why. Could this be related to the body not being created properly?
The world body count is at 2 as I think it should be. I was also thinking that when setting the vector's Y position at my screen height, it's actually getting set at screen height meters rather than pixels. Am I overlooking something obvious?