Game Development Reference
In-Depth Information
Chapter 26
Game Physics
In the previous chapter, you saw how to create an animated character. You also saw how you can
load levels and level status from the local storage and how to build a tile-based game world. One
of the most important aspects is still missing: defining how the character interacts with the game
world . You can make a character move from left to right, but if you simply place the character in
the level, it can only walk on the bottom of the screen. This isn't enough. You want the character to
be able to jump on top of wall tiles and fall down if it moves off a wall tile, and you don't want the
character to fall off the edge of the screen. For these things, you need to implement a basic physics
system. Because it's the character interacting with the world, you implement this physics in the
Player class. There are two aspects to dealing with physics: giving the character the ability to jump
or fall, and handling collisions between the character and other game objects and responding to
these collisions.
Locking the Character in the Game World
The first thing you do is lock the character in the game world. In the examples in Chapter 25, the
character could walk out of the screen without any problem. You can solve this by placing a virtual
pile of wall-type tiles to the left and right of the screen. You then assume that your collision-detection
mechanism (which you haven't written yet) will ensure that the character can't walk through these
walls. You only want to prevent the character from walking out of the left or right side of the screen.
The character should be able to jump out of sight at the top of the screen. The character should also
be able to fall off the game world through a hole in the ground (and die, obviously).
In order to build this virtual pile of wall tiles on the left and right sides of the screen, you have to add
some behavior to the grid of tiles. You don't want to modify the GameObjectGrid class. This behavior
has nothing to do with the grid of game objects, but it's particular to your platform game. Therefore,
you define a new class called TileField that inherits from the GameObjectGrid class. You add a
single method to that class called getTileType , which returns the type of the tile given its x and y
position on the grid. The nice thing about this method is that you allow these indices to fall outside
337
 
Search WWH ::




Custom Search