HTML and CSS Reference
In-Depth Information
// Set our horizontal force
p.fx = 0;
if(Q.inputs['left']) { p.fx -= p.thrustX; }
if(Q.inputs['right']) { p.fx += p.thrustX; }
// Set our vertical force
if(Q.inputs['fire']) {
p.fy = -p.thrustY;
p.asset = "lander_thrust.png";
} else {
p.fy = 0;
p.asset = "lander.png";
// Calculate our y and x acceleration
p.ay = p.gravity + p.fy / p.m; = p.fx / p.m;
// Let our super-class update our x and y
// Force our lander to stay in our box
// and zero out our velocity when we hit a wall
if(p.y < 0) { p.y = 0; p.vy = 0; }
if(p.y > Q.height- p.h) { p.y = Q.height - p.h; p.vy = 0; }
if(p.x < 0) { p.x = 0; p.vx = 0; }
if(p.x > Q.width - p.w) { p.x = Q.width - p.w; p.vx = 0; }
The Ship class extends the MovingSprite class from the last section and overrides the step method to
enable player input and some extra behavior. The update method includes a few different sections. The first sec-
tion calculates the forces acting on the ship by looking at the player input. Pressing the right or left keys adds a
horizontal force, whereas pressing the spacebar adds a vertical force. The class also swaps the asset for the sprite
to show the lander_thrust.png graphic when the ship accelerates upward. Next, the current acceleration
is calculated from those forces, a gravity constant and the ship's mass property. With the acceleration updated,
the parent's method to update the velocity and position is called. Finally, a bounds check to make sure the ship
stays on the screen is needed.
Next the Ship needs to actually be put into the game. After the standard perfunctory loading and stage setup
details, you create a background sprite and a new ship object with an initial x and y location, along with an
initial mass and gravity. Add the code from Listing 17-6 to the bottom of lander.html before the closing
</script> tag.
Listing 17-6: The basic Lander game code
'lander_thrust.png','map.png'], function() {
Search WWH ::

Custom Search