1

So I am making a top down game where the player moves using WASD keys. For this I use

if (Gdx.input.isKeyPressed(Input.Keys.S) && b2dBody.getLinearVelocity().y >= -0.8) {
    b2dBody.applyLinearImpulse(new Vector2(0, -PLAYER_SPEED), b2dBody.getWorldCenter(), true);
} else if (Gdx.input.isKeyPressed(Input.Keys.W) && b2dBody.getLinearVelocity().y <= 0.8) {
    b2dBody.applyLinearImpulse(new Vector2(0f, PLAYER_SPEED), b2dBody.getWorldCenter(), true);
} else if (Gdx.input.isKeyPressed(Input.Keys.A) && b2dBody.getLinearVelocity().x >= -0.8) {
    b2dBody.applyLinearImpulse(new Vector2(-PLAYER_SPEED, 0), b2dBody.getWorldCenter(), true);
} else if (Gdx.input.isKeyPressed(Input.Keys.D) && b2dBody.getLinearVelocity().x <= 0.8) {
    b2dBody.applyLinearImpulse(new Vector2(PLAYER_SPEED, 0), b2dBody.getWorldCenter(), true);
}

But because the gravity is set to 0 world = new World(new Vector2(0, 0), true); the body doesn't stop. I was wondering if there was a way to keep the gravity the same while making the body stop after after a while? Thanks in advance.

Unused hero
  • 307
  • 1
  • 9
playper3
  • 67
  • 5
  • 1
    See if this helps: https://stackoverflow.com/questions/24417977/libgdx-implementing-moving-kinematic-body – markspace Sep 05 '21 at 20:15
  • 1
    Some terminology I've learned: in games, a "kinematic" body means something that moves, but is not a physics object. Examples include a player avatar and a simple moving platform. So I think you want to be using kinematic bodies, not applying forces to physics bodies. I'm not an expert in libGDX so take that with a grain of salt. – markspace Sep 05 '21 at 20:18

1 Answers1

1

When you create a box2d body you can set the linearDamping value of the BodyDef object that is used to create the body.
This value will always slow down the object when it's moving (e.g. when applying a linear impulse).

You can use it like this:

BodyDef bodyDef = new BodyDef();
//set other body values
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(42f, 42f);
bodyDef.angle = 0f;
//...
bodyDef.linearDamping = 10f; // this will make the body slow down when moving

//create the body
Body body = world.createBody(bodyDef);

// TODO move the body arround and it will automatically slow down
Tobias
  • 2,547
  • 3
  • 14
  • 29