Game Development Reference
In-Depth Information
Force, impulse, and linear velocity
Let's jump straight to the point with some new lines in the
Main
function:
public function Main() {
world=new b2World(new b2Vec2(0,10),true);
debugDraw();
floor();
sphereVector=new Vector.<b2Body>();
for (var i:int=0; i<3; i++) {
sphereVector.push(sphere(170+i*150,410,40));
}
var force:b2Vec2=new b2Vec2(0,-15);
var sphereCenter:b2Vec2=sphereVector[0].GetWorldCenter();
sphereVector[0].ApplyForce(force,sphereCenter);
sphereCenter=sphereVector[1].GetWorldCenter();
sphereVector[1].ApplyImpulse(force,sphereCenter);
sphereVector[2].SetLinearVelocity(force);
addEventListener(Event.ENTER_FRAME,updateWorld);
}
This is the core of this chapter and it's a lot of new stuff, so let's look at it line by line:
var force:b2Vec2=new b2Vec2(0,-15);
First, we need to create a
b2Vec2
variable that will represent the force we want to
apply to all spheres. Setting it at
(0,-15)
means this is a vertical force, which should
make the spheres jump.
Having a force is not enough if we don't have a point at which to apply the force.
In this case, we want the force to be applied to the center of the mass of each sphere.
var sphereCenter:b2Vec2=sphereVector[0].GetWorldCenter();
To determine the center of the mass of a body, we can use the
GetWorldCenter
method of
b2Body
. It returns a
b2Vec2
object with the center of the mass.
In this case, the
sphereCenter
variable will contain the center of the left sphere.
sphereVector[0].ApplyForce(force,sphereCenter);
The previous line of code shows the first way to apply a force to a body. The
ApplyForce
method applies a force at a point, usually in newton. If the force
is not applied at the center of the mass, it will generate a torque and affect the
angular velocity, and that's why we wanted to know the center of the mass. The
ApplyForce
method also wakes up the body, if it is in the inactive sleep state.
sphereCenter=sphereVector[1].GetWorldCenter();