I'm fooling around with Box2D and libGDX and running into a peculiar problem with polling for input. Here's the code for the Screen's render() loop:

public void render(float delta) {
    Gdx.gl20.glClearColor(0, 0, .2f, 1);
    debugRenderer.render(world, camera.combined);
        Gdx.app.log("Input", "Left is being pressed.");
        pushyThingyBody.applyForceToCenter(-10f, 0);
        Gdx.app.log("Input", "Right is being pressed.");
        pushyThingyBody.applyForceToCenter(10f, 0);
    world.step((1f/45f), 6, 2);

And the constructor is largely just setting up the World, Box2DDebugRenderer, and all the Bodies in the world:

public SandBox(PhysicsSandboxGame game) {
    this.game = game;
    camera = new OrthographicCamera(800, 480);

    world = new World(new Vector2(0, -9.8f), true);
    debugRenderer = new Box2DDebugRenderer();

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyType.DynamicBody;
    bodyDef.position.set(100, 300);

    body = world.createBody(bodyDef);

    CircleShape circle = new CircleShape();

    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = circle;
    fixtureDef.density = .5f;
    fixtureDef.friction = .4f;
    fixtureDef.restitution = .6f;

    fixture = body.createFixture(fixtureDef);

    BodyDef groundBodyDef = new BodyDef();
    groundBodyDef.position.set(new Vector2(0, 10));
    groundBody = world.createBody(groundBodyDef);
    PolygonShape groundBox = new PolygonShape();
    groundBox.setAsBox(camera.viewportWidth, 10f);
    groundBody.createFixture(groundBox, 0f);

    BodyDef pushyThingyBodyDef = new BodyDef();
    pushyThingyBodyDef.type = BodyType.DynamicBody;
    pushyThingyBodyDef.position.set(new Vector2(400, 30));
    pushyThingyBody = world.createBody(pushyThingyBodyDef);
    PolygonShape pushyThingyShape = new PolygonShape();
    pushyThingyShape.setAsBox(40f, 10f);
    FixtureDef pushyThingyFixtureDef = new FixtureDef();
    pushyThingyFixtureDef.shape = pushyThingyShape;
    pushyThingyFixtureDef.density = .4f;
    pushyThingyFixtureDef.friction = .1f;
    pushyThingyFixtureDef.restitution = .5f;
    pushyFixture = pushyThingyBody.createFixture(pushyThingyFixtureDef);

Testing this on the desktop. Basically, whenever I hit the appropriate keys, neither of the if statements in the loop return true. However, when I click in the window, both statements return true, resulting in a 0 net force on the body. Why is this?


1 Answer 1


It seems you're mixing up the keyboard and mouse a little bit. Your line: if(Gdx.input.isButtonPressed(Keys.LEFT)) {

should either be:

if(Gdx.input.isKeyPressed(Keys.LEFT)) { (Keys Javadoc if you're wanting keyboard input)


if(Gdx.input.isButtonPressed(Buttons.LEFT)) { (Buttons Javadoc if you want mouse input)

I'm not sure if you've got any other problems just by looking at your code.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .