Game Development Reference
In-Depth Information
problem can be solved by keeping track of whether the game is paused. Basically, you need to
maintain a time offset that increases while the game is paused. Many first-person shooters follow
this strategy because in those kinds of games, it's crucial to have a high framerate so the player can
interact naturally with the game world. And with first-person shooters, chances are the players are
completely involved in the game, and they wouldn't dream of interrupting the game to read the news
or play a Sudoku!
Controlling the Visibility of a Game Object
In this section you create a class that controls the visibility of a game object based on a timer. Let's
call this class
VisibilityTimer
. The idea of this class is that you can assign it a target game object,
for which visibility is set to
false
by default; when you start the timer, the target object becomes
visible until the timer has reached its maximum value. You can connect such a timer to an overlay
in order to show that overlay on the screen for a while. Take a look at the
JewelJamFinal
program
belonging to this chapter; it contains a file called
VisibilityTimer.js
that includes the complete
VisibilityTimer
class.
A visibility timer object needs to keep track of a couple of things. For one, you need to store
the target object whose visibility you want to control. You also store how much time in total this
object should be visible, for when the timer is started. Finally, when the timer is running you have
to maintain how time is left before it stops. This value is updated every time the
update
method is
called. Therefore, the
VisibilityTimer
class inherits from the
GameObject
class.
When the timer is created, you assume it isn't running, so the time left is set to 0. You also set the
total time that the timer should run to 1 second:
function VisibilityTimer(target, layer, id) {
GameObject.call(this, layer, id);
this._target = target;
this._timeLeft = 0;
this.totalTime = 1;
}
In the
update
method, you then subtract the elapsed game time in seconds from the
_timeLeft
variable. If this variable contains a value less than zero, you set the target visibility to
false
:
VisibilityTimer.prototype.update = function (delta) {
if (this._timeLeft > 0) {
this._timeLeft -= delta;
this._target.visible = true;
} else
this._target.visible = false;
};
Finally, you add a method called
startVisible
that assigns the total time to the
_timeLeft
variable
and sets the targets visibility status to
true
.
Search WWH ::
Custom Search