Game Development Reference
In-Depth Information
how the variables were related to each other or what you could do with them. By grouping variables
in objects and providing methods that belong with these objects, you can write programs that are
much easier to understand. In the next section, you use this power in a simple example that moves a
square around the canvas.
The MovingSquare Game
This section examines a simple program that moves a square over the canvas. Its purpose is to
illustrate two things:
update and draw parts of a game loop work in more detail
How to use objects to structure a program
How the
Before you start writing this program, let's look at the code of the BasicGame example one more time:
var canvas = undefined;
var canvasContext = undefined;
function start () {
canvas = document.getElementById("myCanvas");
canvasContext = canvas.getContext("2d");
mainLoop();
}
document.addEventListener('DOMContentLoaded', start);
function update () {
}
function draw () {
canvasContext.fillStyle = "blue";
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
}
function mainLoop () {
update();
draw();
window.setTimeout(mainLoop, 1000 / 60);
}
What you have here are a couple of variable declarations and a few functions that do something with
those variables. With your new knowledge about grouping variables together in objects, let's make it
clear that all these variables and functions belong to a game application, as follows:
"use strict";
var Game = {
canvas : undefined,
canvasContext : undefined
};
 
Search WWH ::




Custom Search