Tuesday 10 January 2012

JBox2D with JavaFX tutorial: Applying Force and Impulse on body

Many times there will be situation when in JBox2D world we want to move bodies manually. So how do we do it? In real world we apply force to move anything. It holds good in JBox2D world too. To move bodies in JBox2D world we have to apply Force or Impulse.

There is a difference between force and Impulse. Force act gradually on bodies’ velocity. Imagine in real world if we wants to move one big box from one location to other then we will start pushing it. It means we will gradually apply force on that box; as a result box will start moving. Force in JBox2D world also works in similar fashion.

Following is a code snippet for applying force on body.
Body body = (Body)ball.getUserData();
Vec2 force  = new Vec2(0, 150.0f);
Vec2 point = body.getWorldPoint(body.getWorldCenter());
body.applyForce(force ,point);

Impulse act instantaneously, in a fraction of time step. Impulse is like we strike snooker ball with a cue or move objects with the help of explosives. Applying impulse is similar to applying force. We need to use applyLinearImpulse() function in place of applyForce()

Following sample code snippet is for applying the impulse.
Body body = (Body)ball.getUserData();
Vec2 force  = new Vec2(0, 50.0f);
Vec2 point = body.getWorldPoint(body.getWorldCenter());
body. applyLinearImpulse (force ,point);

The applyForce() and applyLinearImpulse() function takes two parameters force and point. Force parameter defines a direction and magnitude of the force. And second parameter defines on which point of the body force should be applied. In above snippet, we are applying force/impulse on center of the body.

<<JBox2D With JavaFX : Write your first JBox2D with JavaFX 2 program

1 comment:

  1. Peyronie's disease is where plaques (segments of flat scar tissue) form under the skin of the penis. These plaques can cause the penis to bend or become indented during erections. The plaques can often be felt through the skin and can be painful, use Natural Treatments for Peyronie's Disease relief a painful disorder.

    ReplyDelete