Search code examples
javalibgdxbox2d

Simple way to move Box2D Body


In plain java, you can just add values to the coordinates like:

object.x += 5;
object.y += 5;
render(object, object.x, object.y);

Is there any way to do this to a Box2D body? Because if I do this:

if(Gdx.input.isKeyPressed(Input.Keys.A) && player.getBody().getLinearVelocity().x >= -2.0f) {
            player.getBody().applyLinearImpulse(new Vector2(-0.12f, 0.0f), player.getBody().getWorldCenter(), true);
        }

then the object keeps going in that direction until I apply a different force. So is there any way to move it a constant amount instead of keep on moving it forever in a constant velocity? I have tried experimenting with friction but it seems like a pain.


Solution

  • Peter's code also works but I found another way since setTransform may cause potentially unwanted failures:

        float velX = 0, velY = 0;
        if(Gdx.input.isKeyPressed(Input.Keys.W)) {
            velY = 2.0f ;
        } else if(Gdx.input.isKeyPressed(Input.Keys.D)) {
            velX = 2.0f;
        } else if(Gdx.input.isKeyPressed(Input.Keys.S)) {
            velY = -2.0f;
        } else if(Gdx.input.isKeyPressed(Input.Keys.A)) {
             velX = -2.0f;
        }
    
        player.getBody().setLinearVelocity(velX, velY);
    

    Whenever a key is pressed, the velX or the velY is set and if nothing is pressed, they are set to 0 by default.