3D Game Programming

(C. Jardin) #1
The bulk of this function is dedicated to setting the color and opacity (how
easy it is to see through) of the goal light. If the opacity used to be 0.4, then
we set it to 0.15 (making it easier to see through) and change the spotlight
color to white.

Otherwise, we set the color to red and the opacity to 0.4. That’s the bulk of
the function, but not the most interesting part.

When flashGoalLight() is called, it’s called with the goal light that we want to
flash and the number of flashes that remain. When we called flashGoalLight()
back in the collision event, we didn’t tell it how many times remained to be
flashed—we called it with no parameters. If a JavaScript function is called
without all of its parameters, the parameters are undefined, which we first
talked about back in Section 7.2, Describing a Thing in JavaScript, on page
67.

In this case, if remaining is undefined, then it is the first time the function has
been called, and we set it to 9 more times that we flash the light.

The really interesting thing about this function happens at the end. If the
number of flashes remaining is more than zero, we call the function again
—from inside itself.

if(remaining > 0) {
setTimeout(function() {flashGoalLight(light, remaining-1);}, 500);
}

This is a real-world example of recursion, which we first encountered back
in Functions: Use and Use Again.

In this case, we call the same flashGoalLight() with the same light parameter,
but we subtract one from the number of flashes remaining. So we call it with
eight remaining, which then calls it with seven remaining, and so on, all the
way down to zero remaining. When there are zero remaining we simply do
not call flashGoalLight() again, and the recursion stops.

Also in this last bit of code is setTimeout(). This calls the function after waiting
a little bit. In this case we’re waiting 500 milliseconds, or half a second.

With that, we’re done with the goal, so move back on up to the code outline
and uncomment the call to addGoal().

Add a Background


Let’s add our starry background from Chapter 13, Project: Build Your Own
Solar System, on page 117, to this game. Below the addGoal() function definition,
add the following:

report erratum • discuss

Outline the Game • 155


Prepared exclusively for Michael Powell

Free download pdf