Pacman Ghost Algorithm

In a game of Pacman a specific algorithm is used to control the movement of the ghosts who are chasing (running towards) Pacman.

For this challenge we will assume that ghosts can walk through walls (as ghosts do!). So we will implement an algorithm that is slightly different to the algorithm used in the real game of Pacman where ghosts can only run alongside the corridors of the maze.

Our algorithm will be used in a frame based game where the sprites (e.g. Pacman, Ghosts) are positioned using (x,y) coordinates. The Pacman movement will be based on the position of the mouse cursor whereas the Ghosts will use a velocity vector (vx,vy) to move/translate between two frames.


Trigonometric Ratios: SOH-CAH-TOA

Our algorithm will use the trigonometric ration to find the angle the Ghost needs to head towards to chase Pacman.

The next step of our algorithm will use this angle to calculate the velocity vector (Vx,Vy) of the ghost:

The final step of our algorithm will update the (x,y) coordinates of our ghost to apply the velocity vector translation before drawing the ghost sprite on the screen.

Python Code

Did you like this challenge?

Click on a star to rate it!

Average rating 2.4 / 5. Vote count: 17

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: