Game Development Reference
In-Depth Information
Now the only thing you need to do is calculate what the x-position of the rectangle should be.
You do this in the update method, because changing the x-position of the rectangle means you're
updating the game world . In this simple example, let's change the position of the rectangle based on
the time that has passed. In JavaScript, you can use the following two instructions to get the current
system time:
var d = new Date();
var currentSystemTime = d.getTime();
You have not seen the kind of notation used in the first line before. For now, let's assume that
new Date() creates a composite variable (object) that is filled with date and time information as well
as a couple of useful methods. One of these methods is getTime . You call that method on the object
d and store its result in the variable currentSystemTime . This variable now contains the number of
milliseconds that have passed since January 1, 1970 (!). You can imagine that this number is quite
large. If you wanted to set the x-position to that value, you would require a computer monitor with
a huge resolution. This monitor would certainly never fit in your room (or any room, for that matter).
Instead, you divide the system time by the width of the canvas, take the remainder of that division,
and use that as the x-position of the rectangle. That way, you always get an x-position between zero
and the width of the canvas. Here is the complete update method that does this:
Game.update = function () {
var d = new Date();
Game.rectanglePosition = d.getTime() % Game.canvas.width;
};
As you know, the update and draw methods are called in sequence, about 60 times per second.
Every time this happens, the system time has changed (because time has passed), meaning the
position of the rectangle will be changed, and it will be drawn in a different position than before.
You need to do one more thing before this example will work as it should. If you were to run the
program like this, a blue bar would appear on the screen. The reason is that you're currently drawing
the new rectangle on top of the old one. In order to solve this, you need to clear the canvas every
time before you draw on it again. Clearing the canvas is done by the clearRect method. This method
clears a rectangle of a given size of anything that was drawn in it. For instance, this instruction clears
the entire canvas:
Game.canvasContext.clearRect(0, 0, Game.canvas.width, Game.canvas.height);
For convenience, you put this instruction in a method called clearCanvas , as follows:
Game.clearCanvas = function () {
Game.canvasContext.clearRect(0, 0, Game.canvas.width, Game.canvas.height);
};
 
Search WWH ::




Custom Search