Hello, I’m trying to implement player movement into my game using Box2D. Through applying linear impulses, the player is able to move around and jump, but, whenever the player jumps and move around, they appear to glide around.
@Override
public void update(float deltaTime) {
super.update(deltaTime);
Body body = this.getComponent(PhysicsComponent.class).body;
Vector2 pos = body.getPosition();
if(moveLeft) {
body.applyLinearImpulse(new Vector2(-walkSpeed, 0F), pos, true); //move left
facing = Direction.LEFT;
}
if(moveRight) {
body.applyLinearImpulse(new Vector2(walkSpeed, 0F), pos, true); //move right
facing = Direction.RIGHT;
}
if(!moveLeft && !moveRight) {
Vector2 vel = body.getLinearVelocity();
body.applyForce(new Vector2(-vel.x * 10F, 0F), pos, true); //stop
walkTime = 0F;
idleTime += deltaTime;
} else {
idleTime = 0F;
walkTime += deltaTime;
}
}
public void jump() {
Body body = this.getComponent(PhysicsComponent.class).body;
Vector2 pos = body.getPosition();
body.applyLinearImpulse(new Vector2(0F, 100F), pos, true); //jump
}
If I don’t move horizontally while falling, everything seems to be okay.