Java Reference
In-Depth Information
clownNode
, and restarts the
Timeline
powerAnim
. The
Timeline
powerAnim
causes the value of
cannonPower
to change from 0 to 1000 over 1 second. When the value of
cannonPower
changes, a new
LinearGradient
is
applied to the
Node
powerFill
. This is what animates the power bar on the upper left of the scene.
Once
readyLaunch
is called, the game is ready for the user to fire the clown. When the user clicks the
mouse button or presses the spacebar, the function
fireClown
is called. The function
fireClown
stops the
Timeline
powerAnim
and uses the current value of
cannonPower
and the current value of
cannonAngle
to
create a new
ClownBody
. The class
ClownBody
is used to synchronize the position and rotation of the
Node
clownNode
with the
Body
that represents the clown in flight. Listing 11-5 shows the class
ClownBody
.
Listing 11-5.
ClownBody.fx
public class ClownBody {
public-init var startingPower:Number;
public-init var clown:Node;
public var body:Body;
init{
body = new Body(new net.phys2d.raw.shapes.Circle(4), 1);
body.setPosition(clown.translateX, clown.translateY);
var rotationInRadians = Math.toRadians(clown.rotate);
var x = Math.cos(rotationInRadians) * startingPower;
var y = Math.sin(rotationInRadians) * startingPower;
body.adjustVelocity(new Vector2f(x,y));
}
public function update():Void{
clown.translateX = body.getPosition().getX();
clown.translateY = body.getPosition().getY();
var velocity = body.getVelocity();
var vX = velocity.getX();
var vY = velocity.getY();
var tanTheta = vY/vX;
var arcTan = Math.atan(tanTheta);
clown.rotate = Math.toDegrees(arcTan);
}
}
In Listing 11-5 we see that the class
ClownBody
does a few things. When the
init
function is called, a
new
Body
is created, and its position and rotation are set the same as the
Node
clown
. The
Body
is also
given an initial velocity based on the angle of the cannon and the
startingPower
. The
update
function is
called by
GameMode
to synchronize the position and rotation of the
Node
clown
based on the position and
velocity of the
body
. By setting the rotation of the
Node
clown
based on the velocity of
body
keeps
clown
pointed in the direction it is traveling.
Once the clown is prepared to fly through the scene by the function
fireClown
, the
Timeline
worldUpdater
is started, which calls the function
update
every 30th of a second. The function
update
advances
world
by one step and updates the location of
flyingClown
. The function
update
also checks to
see if the clown has intercepted the balloon, if the clown has landed in the bucket, and lastly, if the clown