I am making a 2D platformer in LibGDX with both Ashley and Box2D.
I have it so, that the PlayerControllerSystem
watches for the jump key being pressed:
// Jumping
if (Gdx.input.isKeyPressed(Keybindings.KEY_JUMP)) {
entity.add(new JumpingComponent());
}
This works like a charm. Every time I press the jump key the PlayerJumpingSystem
fires up:
/**
* System used for the player jumping mechanism
* @author Tim
*/
public class PlayerJumpingSystem extends IteratingSystem {
@SuppressWarnings("unused")
private final static String TAG = PlayerJumpingSystem.class.getName();
// Variable declaration
@SuppressWarnings("unchecked")
private static final Family family = Family.all(
PositionComponent.class,
VelocityComponent.class,
PhysicsComponent.class,
PlayerComponent.class,
JumpingComponent.class).get();
public PlayerJumpingSystem () {
super(family);
}
@Override
protected void processEntity (Entity entity, float deltaTime) {
PositionComponent position = Mappers.position.get(entity);
VelocityComponent velocity = Mappers.velocity.get(entity);
PhysicsComponent physics = Mappers.physics.get(entity);
if (velocity.y > 0) {
// We are ascending
physics.body.applyLinearImpulse(0, -Constants.JUMP_FORCE, position.x, position.y, true);
}
if (velocity.y < 0) {
// We are descending
physics.body.applyLinearImpulse(0, Constants.JUMP_FORCE, position.x, position.y, true);
}
else if (velocity.y == 0) {
entity.remove(JumpingComponent.class);
Gdx.app.log(TAG, "JumpingComponent removed");
}
}
}
It gives very weird jumping behaviour. Does anyone know how to implement jumping with Box2D in a good way? Thanks in advance!