Path finding in a Java 2d Game?

Click Upvote picture Click Upvote · Mar 8, 2009 · Viewed 15.1k times · Source

Essentially its a pacman clone game I'm working on. I have an Enemy class, and 4 instances of this class created which all represent 4 ghosts of the game.

All ghosts start up in random areas of the screen and then they have to work their way towards the pacman character. As the player controls the pacman, moving it around, they should follow it and take the nearest possible way towards him.

There is no maze/obstacles (yet) so the entire map (400x400 pixels) is open ground to them.

For the player and each Ghost, i can retrieve the X, Y, image width and height attributes. Also, i already have a collision detection algorithm, so not worried about that, just about the ghosts finding their way to pacman.

Answer

coobird picture coobird · Mar 8, 2009

For a good pathfinding algorithm, using A* would probably be a good idea, however, for a simple game that doesn't require sophisticated, efficient, nor effective path searching, simply having the characters move toward a target by finding out the direction of the target should be sufficient.

For example, the decision to make the character move, in pseudocode:

if (target is to the left of me):
    move(left);
else
    move(right);

if (target is above me):
    move(up);
else
    move(down);

Yes, the character is not going to make the most efficient movement, but it will get closer and closer to the target on each iteration of the game loop.

It's also my guess that an arcade game from the early 80's probably wouldn't be using sophisticated pathfinding algorithms.