# Running and Jumping using Box2d and libgdx

.this is my first trial on making a 2d game and currently struglling how to run and jump smoothly. My problem is when the player keep pressing on left or right botton then jump. the player won't jump, also when keep on holding left or right. the speed gets faster

if (KeyInput.isPressed(KeyInput.Button.JUMP)) {
body.applyForceToCenter(0, playerJumpForce, true);
}

if (KeyInput.isDown(KeyInput.Button.LEFT)) {
body.setLinearVelocity(new Vector2((body.getLinearVelocity().x - (playerSpeed * delta)), 0));
}

if (KeyInput.isDown(KeyInput.Button.RIGHT)) {
body.setLinearVelocity(new Vector2((body.getLinearVelocity().x + (playerSpeed * delta)), 0));
}


## 1 Answer

You don't want to use setLinearVelocity for horizontal movement as that set's the velocity to a value it will cancel out any force applied because of a jump.

For moving left and right you want to use either applyForceToCenter (like what you do for your jump), or applyLinearImpulse.

You might want your code to do something like this to limit the ever increasing speed when walking;

if (KeyInput.isPressed(KeyInput.Button.JUMP)) {
body.applyForceToCenter(0, playerJumpForce, true);
}

if (KeyInput.isDown(KeyInput.Button.LEFT)) {
body.applyForceToCenter(Math.abs(body.getLinearVelocity().x) < MAX_SPEED ? speed * deltaTime, 0));
}

if (KeyInput.isDown(KeyInput.Button.RIGHT)) {
body.applyForceToCenter(Math.abs(body.getLinearVelocity().x) < MAX_SPEED ? -speed * deltaTime, 0));
}


Also note that you will probably need to detect if the player is standing on the ground and only allow jumping then.