Hey guys, i’ve started playing a little bit around with libGDX and box2d. It’s pretty straight forward and very nice but somehow I cant manage to move a body with WASD. I googled a lot but could not finde a solution for my problem.
This is my method for handlingInput:
float velX = 0, velY = 0;
if(Gdx.input.isKeyPressed(Input.Keys.W)) {
velY = 200.0f ;
} else if(Gdx.input.isKeyPressed(Input.Keys.D)) {
velX = 200.0f;
} else if(Gdx.input.isKeyPressed(Input.Keys.S)) {
velY = -200.0f;
} else if(Gdx.input.isKeyPressed(Input.Keys.A)) {
velX = -200.0f;
}
else {
velX = 0;
velY = 0;
}
mPlayer.setLinearVelocity(velX, velY);
The position gets updated correctly if I check it with a sysout. My problem is that the box2ddebugrenderer which I use does not update the body accordingly. This might also be a camera problem I assume.
These are my draw and update methods which I call inside of render.
/**
* Used only for graphic to draw stuff
*/
private void draw() {
mBatch.setProjectionMatrix(mCamera.combined);
mB2dr.render(mWorld, mCamera.combined);
}
/**
* Main update method used for logic
* @param delta delta time received from {@link PlayScreen#render(float)} method
*/
private void update(final float delta) {
mCamera.position.set(mPlayer.getPosition(), 0);
mCamera.update();
mWorld.step(delta, 6, 2);
}
And last but not least the constructor for my screen:
public PlayScreen() {
mBatch = new SpriteBatch();
mWorld = new World(new Vector2(0,0), true);
mB2dr = new Box2DDebugRenderer();
mCamera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
mCamera.zoom = 10f;
mViewport = new FitViewport(Gdx.graphics.getWidth() / 50, Gdx.graphics.getHeight() / 50, mCamera);
mPlayer = ShapeFactory.createRectangle(new Vector2(0,0), new Vector2(32,32), BodyType.DynamicBody, mWorld, 0.0f);
}
As I said the position gets updated correctly on pressing a button. But the box2renderer does not display the new position of the square. I couldnt find anything on the web regarding this.
If I press “W” for example the rectangle moves up (teleporting - only once) and when I release the button the rectangle gets teleported back to its starting position. The position is increased correctly though. Similiar behavior for the other buttons. I assume that somehow my camera setup is flawed ???
Thanks in advance!
PS. I also call
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
inside of my render method.