Game Development Reference
In-Depth Information
Game.start = function () {
Game.canvas = document.getElementById("myCanvas");
Game.canvasContext = Game.canvas.getContext("2d");
Game.mainLoop();
};
document.addEventListener('DOMContentLoaded', Game.start);
Game.update = function () {
};
Game.draw = function () {
Game.canvasContext.fillStyle = "blue";
Game.canvasContext.fillRect(0, 0, Game.canvas.width, Game.canvas.height);
};
Game.mainLoop = function () {
Game.update();
Game.draw();
window.setTimeout(mainLoop, 1000 / 60);
};
The main thing you do here is create a single composite variable (object) called Game . This object has
two member variables : canvas and canvasContext . In addition, you add a number of methods to this
object, including the methods that together form the game loop. You define the methods belonging
to this object separately (in other words, they aren't a part of the variable declaration and initial
assignment). The reason is that you can now easily distinguish the data the object consists of from
the methods that do something with the data . Note also that you add the instruction "use strict";
to the program, as I promised!
Now let's extend this example so it shows a smaller rectangle moving on the screen. You want to
change the x-position of the rectangle over time. In order to do that, you have to store the current
x-position of the rectangle in a variable. That way, you can assign a value to that variable in the
update method (where you change the game world) and use the variable to draw the rectangle on
the screen in the draw method (where you draw the game world on the screen). The logical place to
add this variable is as a part of the Game object, so you declare and initialize this object as follows:
var Game = {
canvas : undefined,
canvasContext : undefined,
rectanglePosition : 0
};
You use the variable rectanglePosition to store the desired x-position of the rectangle. In the draw
method, you can then use that value to draw a rectangle somewhere on the screen. In this example,
you draw a smaller rectangle that doesn't cover the entire canvas so you can see it move around.
This is the new draw method:
Game.draw = function () {
Game.canvasContext.fillStyle = "blue";
Game.canvasContext.fillRect(Game.rectanglePosition, 100, 50, 50);
}
 
Search WWH ::




Custom Search