Game Development Reference
In-Depth Information
Have a look at the Ball.js file in the Painter5 example belonging to this chapter. You can see the
Ball class and all its methods. Note that I didn't add any functionality to the balls; I only applied
the prototype principle to define the blueprint for balls .
The concept of classes and objects is extremely powerful. It forms the basis of the object-oriented
programming paradigm . JavaScript is a very flexible language, in that it doesn't oblige you to use
classes. You could write scripts using only functions if you wanted to (and this is what you've done
until now). But because classes are such a powerful programming concept and are widely used in
the (game) industry, this topic exploits them as much as possible. By learning how to properly use
classes, you can design much better software, in any programming language.
Note When programming games, you often have to make a trade-off between how long it takes to do
something and how often you do it. In the case of Painter, if you're only ever going to create one or two balls,
then it might not be worth going through the trouble of creating a class for the balls. However, it's often the case
that things scale up slowly. Before you know it, you're copying and pasting dozens of lines of code because
you didn't create an easier way to do it once. When you design your classes, consider the long-term gains of
a proper design, even if that requires a short-term sacrifice such as having to do some extra programming
work to make the class design more generic.
Constructing Game Objects as Part of the Game World
Now that you've seen how to create classes, you need to rethink where your game objects are
constructed. Until now, game objects were declared as global variables, and as such, they were
accessible everywhere. For example, this is how you create the cannon object:
var cannon = {
};
cannon.initialize = function() {
cannon.position = { x : 72, y : 405 };
cannon.colorPosition = { x : 55, y : 388 };
cannon.origin = { x : 34, y : 34 };
cannon.currentColor = sprites.cannon_red;
cannon.rotation = 0;
};
In the Painter5 example, this is the constructor of the Cannon class:
function Cannon() {
this.position = { x : 72, y : 405 };
this.colorPosition = { x : 55, y : 388 };
this.origin = { x : 34, y : 34 };
this.currentColor = sprites.cannon_red;
this.rotation = 0;
}
 
Search WWH ::




Custom Search