Game Development Reference
In-Depth Information
You did a similar thing in the
Ball
class, except you let the variable of the same name point to
colored ball sprites. Although this works fine, it's slightly inconvenient when the color of a ball needs
to change according to the color of the cannon:
if (Game.gameWorld.cannon.currentColor === sprites.cannon_red)
this.currentColor = sprites.ball_red;
else if (Game.gameWorld.cannon.currentColor === sprites.cannon_green)
this.currentColor = sprites.ball_green;
else
this.currentColor = sprites.ball_blue;
In this
if
instruction, you need to handle all three different colors; furthermore, now the
Ball
class
needs to have knowledge about the sprites that the
Cannon
class uses. Wouldn't it be better if you
could define colors more uniformly and use that definition in all the game-object classes to represent
different colors? Of course it would! Another reason to start unifying the usage of colors in your
games now is that the current approach will take much longer to program if you ever decide to
increase the number of possible colors in the game (to 4, 6, 10, or more).
The Painter7 example belonging to this chapter adds a
Color.js
JavaScript file. To define different
colors, you use an approach similar to what you do to define different keys. This file defines a
variable called
Color
. The
Color
variable contains a number of subvariables, each representing a
different color. You could define colors as follows:
var Color = {
red : 1,
blue : 2,
yellow : 3,
green : 4,
// and so on
}
However, this approach is not such a good solution. Using numbers to represent colors isn't a bad idea,
but you shouldn't make up your own numbering scheme that no one else will know. There is already a
standard for defining colors in HTML that uses integers expressed in
hexadecimal
form, and you can
use that same standard. The advantage is that this approach is widely used, widely understood, and
In the HTML standard, you can define the colors of elements in a web page by using a hexadecimal
representations. For example:
<body style="background: #0000FF">
That's a very nice background.
</body>
In this case, you indicate that the background color of the body should be the color
blue
.
The hexadecimal representation lets you define colors in Red, Green, Blue (RGB) values, where
00
means the color component is absent, and
FF
means the color component is maximal.
The
#
sign isn't a part of the number, it's merely there to indicate to the browser that what follows is a
hexadecimal number instead of a decimal number. So, the
#0000FF
hexadecimal number represents
the color blue,
#00FF00
is green, and
#FF0000
is red. And of course, any blend or gradation of color
Search WWH ::
Custom Search