Game Development Reference
In-Depth Information
Because penguins need to move around on the playing board and you need to interact with them,
you create a class Animal to represent an animal such as a penguin or a seal. Later in this section,
you see what this class looks like. To keep track of which animals are in the game, you maintain an
array as a member variable of the Level class, as you've seen before:
this.animals = [];
In the switch instruction, you then create a normal tile and a penguin, as follows:
t = new Tile(sprites.field, ID.layer_objects);
t.sheetIndex = row + col % 2;
tileField.addAt(t, col, row);
var animalSprite = sprites.penguin;
if (levelData.tiles[row][col] === levelData.tiles[row][col].toUpperCase())
animalSprite = sprites.penguin_boxed;
var p = new Animal(levelData.tiles[row][col], animalSprite, ID.layer_objects_1);
p.position = t.position.copy();
p.initialPosition = t.position.copy();
playingField.add(p);
this.animals.push(p);
break;
You're doing a couple of other things as well. For instance, you want there to be a difference
between normal animals and boxed animals (animals that can't move). You make this distinction
by using either uppercase or lowercase characters. JavaScript knows a method toUpperCase
that converts a character to its uppercase variant. You use that method in the condition of an if
instruction to determine the name of the asset that should be used. After creating the Animal object,
you set its position to the position of the tile you created so it's placed correctly. You also set a
variable called initialPosition to that same value. You do this so that if the player gets stuck and
presses the Retry button, you know the original position of each animal in the level.
In the Animal constructor, you pass the character along as a parameter. You do this so that in the
constructor, you can decide which element of the strip should be selected. You can also check the
character to find out whether you're dealing with a boxed animal. The boxed status is stored in a
Boolean member variable of the Animal class:
this.boxed = (color === color.toUpperCase());
In the next instruction, you use a method called indexOf in a smart way to calculate the animal you
want to show, depending on the character passed as a parameter. The indexOf method checks the
first index of a character in a string. For example:
"game".indexOf('a') // returns 1
"over".indexOf('x') // returns -1
"penguin pairs".indexOf('n') // returns 2
Here is how you use that method to calculate the animal's sheet index:
this.sheetIndex = "brgyopmx".indexOf(color.toLowerCase());
 
Search WWH ::




Custom Search