Lesson 26: Adding and Moving a Ghost

Once you have all of the walls of your maze placed, you should be ready to add in a ghost. You should have the ghost images from the files you downloaded way back in lesson 19.

1. Add the ghost_red.png image to your HTML with as id of redGhost.

2. In the CSS, add #redGhost after #pacman so that they both have a position of absolute.

3. There is, as usual, much to do in the JavaScript. Start by declaring redGhost as a global variable.

4. In loadComplete(), set redGhost = to the redGhost element. Just as you did with pacman, set the properties of redGhost to the desired size and position within the gameWindow.

Now the redGhost should appear in your maze. Make sure the ghost starts in an open position, not hitting a wall.

Currently, when pacman and redGhost collide, nothing happens.

5. At the bottom of loop(), add a hit test. If pacman hits redGhost, display a message in the output div.

Of course, you really want the game to stop.

6. Stop the loopTimer when the game is over, instead of outputting the game over message.

Before moving the ghost, you need to decide how fast the ghost should move.

7. Declare GHOST_SPEED as a global constant and assign it the value of 5, half the speed of pacman.

8. In loop(), move redGhost to the right by the value of GHOST_SPEED. Just as you did with pacman, include the conditional statement to cause redGhost to reappear on the left side of the gameWindow as it dissappears on the right.

Now redGhost should repeatedly move across the gameWindow.

Of course, you don't want redGhost running through the walls. Unfortunately, the hitWall() you previously created only works for pacman.

9. Modify hitWall() so it can be used to check if any element hits a wall. Notice there are two changes that need to be made. You need to add an element variable in the function declaration to store the value of the element that is passed to the function, and you need to use that variable instead of pacman when doing the hit tests.

Now you will no longer call the function using hitWall(), but instead by using hitWall(pacman), hitWall(redGhost), etc..

10. Use Find to search for all the instances of the hitWall() function call and replace them with hitWall(pacman).

In addition to the four instances in tryToChangeDirection(), there is also a hitWall() towards the bottom of loop().

11. Before writing code to prevent redGhost from going through walls, make sure that pacman is still moving about the game screen as intended.

12. Add a line of code in loop(), to move redGhost back to it's original position if he hits a wall.

Now the ghost should move to the right until he hits a wall. redGhost is not the smartest ghost in the world yet, but you will give him some AI (Artificial Intelligence) in the next lesson.