1
\$\begingroup\$

I'm just getting started with Box2d and I'm trying to apply an impulse to a circle but nothing really happens.

First I define ball:

BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.DynamicBody;
bodyDef.position.set(camera.viewportWidth / 2, camera.viewportHeight / 2);
ball = world.createBody(bodyDef);
CircleShape dynamicCircle = new CircleShape();
dynamicCircle.setRadius(50f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = dynamicCircle;
fixtureDef.density = 0.5f;
fixtureDef.friction = 0.4f;
fixtureDef.restitution = 0.6f;
ball.createFixture(fixtureDef);
dynamicCircle.dispose();

then I call this line from inside my inputprocessor

public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    Gdx.app.log("input", "touchDown");
    ball.applyLinearImpulse(new Vector2(0f, 5000f), ball.getPosition(), true);
    return true;
}

Here's the render method:

public void render() {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    debugRenderer.render(world, camera.combined);
    world.step(1 / 60f, 6, 2);
}

I tried logging this and can confirm the touchDown event is triggered, but the impulse never applies.

Am I forgetting some call to make this work? What might be going wrong?

\$\endgroup\$
3
  • \$\begingroup\$ Is world.step called? \$\endgroup\$
    – Anko
    Commented Jan 26, 2015 at 10:13
  • \$\begingroup\$ @Anko only in my render method. \$\endgroup\$
    – mars
    Commented Jan 26, 2015 at 11:55
  • \$\begingroup\$ OK. Unless it logs errors, I think the force should be applying then. Hmm. Potential clue: Box2D's maths are tuned for "moving objects roughly between 0.1 and 10 meters" (the manual § 1.7 Units). You might want to reduce the currently 50f-meter radius of the dynamicCircle just in case the applied force is getting discarded by an approximation. \$\endgroup\$
    – Anko
    Commented Jan 26, 2015 at 13:53

1 Answer 1

1
\$\begingroup\$

In this line

ball.applyLinearImpulse(new Vector2(0f, 5000f), ball.getPosition(), true);

I think the point where you put force it relative to object position, so you put impule in

ball.getPosition() + ball.getPosition()

Try to use

public void applyForceToCenter(Vector2 force, boolean wake)

or

ball.applyLinearImpulse(new Vector2(0f, 5000f), new Vector(0,0), true);

Didn't test.

\$\endgroup\$
2
  • \$\begingroup\$ applying impulse to the center works! but the ball doesn't go up, it rotates instead. is this normal? \$\endgroup\$
    – mars
    Commented Jan 26, 2015 at 22:35
  • \$\begingroup\$ ball.applyLinearImpulse(new Vector2(0f, 5000f), ball.getLocalCenter(), true); \$\endgroup\$
    – mars
    Commented Jan 26, 2015 at 22:36

You must log in to answer this question.

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