Game Development Reference
In-Depth Information
position or its rotation. You can group related variables into different objects to make the fact that
these variables are related clearer in the code. For example, look at this example:
var Canvas2D = {
canvas : undefined,
canvasContext : undefined
};
var Game = {
backgroundSprite : undefined,
};
var cannon = {
cannonBarrelSprite : undefined,
position : { x : 72, y : 405 },
origin : { x : 34, y : 34 },
rotation : 0
};
var Mouse = { position : { x : 0, y : 0 } };
As you can see, you now have a couple of different objects, each containing some of the variables
that were before grouped in the Game object. Now it's much easier to see which variables belong
to the cannon and which variables belong to the canvas. And the nice thing is that you can do the
same thing for methods . For example, you can add the methods for clearing the canvas and drawing
an image on it to the Canvas2D object, as follows:
Canvas2D.clear = function () {
Canvas2D.canvasContext.clearRect(0, 0, this.canvas.width,
this.canvas.height);
};
Canvas2D.drawImage = function (sprite, position, rotation, origin) {
// canvas drawing code
};
Using different objects, as opposed to a single object that contains everything belonging to the
game, makes your code a lot easier to read. Of course, this is only true if you distribute the variables
over the objects in a logical manner . Even for simple games, there are a lot of ways in which you can
organize code. All developers have their own style of doing this. As you read on, you'll discover that
this topic also follows a certain style. You may not agree with that style, or sometimes you might
have approached a problem differently than we do in this topic. That's okay. There is almost never a
single correct solution for programming problems.
Going back to the distribution over objects, you can see that we named most objects beginning with
an uppercase character (such as Canvas2D ), but the cannon object starts with a lowercase character.
We did this for a reason, which we discuss in more detail later. For now, let's just say that the objects
that start with an uppercase character are useful for any game, but the objects whose names start with
a lowercase letter are only used for a particular game. In this case, you can imagine that the Canvas2D
object could be used in any HTML5 game, but the cannon object is only useful for the Painter game.
 
Search WWH ::




Custom Search