Game Development Reference
In-Depth Information
Once we have applied the force on the left sphere, let's move on to the middle one.
We determine its center just like before, and then it's time to add another kind of force.
sphereVector[1].ApplyImpulse(force,sphereCenter);
The
ApplyImpulse
method applies an impulse at a point, usually in newton-second,
immediately modifying its velocity. It also modifies the angular velocity if the point
of application is not at the center of the mass, which is not in this case, and wakes up
the body.
Now that we are done with the middle sphere, let's see the right sphere:
sphereVector[2].SetLinearVelocity(force);
The
SetLinearVelocity
method sets the linear velocity of the center of the mass.
It does not need a second argument such as
ApplyForce
and
ApplyImpulse
as it's
always working in the center of the mass.
Are you wondering how the spheres will react to these forces? We need to add some
code to measure what's going on with them, so first we are going to store sphere's
vertical position into the
userData
property in the
sphere
function:
private function sphere(pX:int,pY:int,r:Number):b2Body {
var bodyDef:b2BodyDef=new b2BodyDef();
bodyDef.position.Set(pX/worldScale,pY/worldScale);
bodyDef.type=b2Body.b2_dynamicBody;
bodyDef.userData=pY;
var circleShape:b2CircleShape;
circleShape=new b2CircleShape(r/worldScale);
var fixtureDef:b2FixtureDef=new b2FixtureDef();
fixtureDef.shape=circleShape;
fixtureDef.density=2;
fixtureDef.restitution=0.4;
fixtureDef.friction=0.5;
var theSphere:b2Body=world.CreateBody(bodyDef);
theSphere.CreateFixture(fixtureDef);
return theSphere;
}
There's no need to say how versatile and what a lifesaver
userData
is when we need
to store custom information of a body.
Now, it's time to print some text in the output window, changing
updateWorld
in
the following way:
private function updateWorld(e:Event):void {
var maxHeight:Number;
var currHeight:Number;