I've recently started using libGDX and box2D, and I've created a platformer that uses applyLinearImpulse to jump vertically and it works well. However, when I try to apply an impulse in the x direction to create a dash, it doesn't work.
This code works as intended:
if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE) && jumpCounter < 2) {
float force = body.getMass() * 18;
body.setLinearVelocity(body.getLinearVelocity().x,0);
body.applyLinearImpulse(new Vector2(0, force), body.getPosition(), true);
jumpCounter ++;
}
But when I try to apply it in the same way in the x direction it does not work.
if(Gdx.input.isKeyJustPressed(Input.Keys.K)) {
float force = body.getMass() * 18;
body.applyLinearImpulse(new Vector2(force, 0), body.getPosition(), true);
}
This is all I've done to set up my world, so I'm not sure if there is another method needed.
this.world = new World(new Vector2(0,-25f), false);
And this is how the body is created.
public static Body createBody(float x, float y, float width, float height, boolean isStatic, World world) {
BodyDef bodyDef = new BodyDef();
bodyDef.type = isStatic ? BodyDef.BodyType.StaticBody : BodyDef.BodyType.DynamicBody;
bodyDef.position.set(x/32.0f, y/32.0f);
bodyDef.fixedRotation = false;
Body body = world.createBody(bodyDef);
PolygonShape shape = new PolygonShape();
shape.setAsBox(width/2/32.0f, height/2/32.0f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.density = 0.2f;
fixtureDef.shape = shape;
fixtureDef.friction=0;
body.createFixture(fixtureDef);
shape.dispose();
return body;
What would need to be changed for this impulse to work?