# Random 4-Directions Patrolling in Maze

I’m about to make my first Game and got stuck on the very beginning. I have a maze like structure and need my sprites patrolling the maze in random ways. Think of the Ghosts in PacMan. My fist idea was to detect a collision with any wall and choose randomly one of 4 directions to move along (I do not use diagonal). But that does not work - they always “bounce” back and forth.

The second (and I think far better) idea was to position invisible objects on every junction. So when an enemy overlaps with such an object I know he is on a junction, and I changes his direction randomly.

But how can I detect if a enemy is on a junction? I could not find something like “if sprite1 is on sprite2”? Is there a way to detect this?

Or is there any better way to create a random 4-way movement in a maze?

A viable way to make it is to use the pathfinding behavior and choose a random spot close to the object (like RandomInRange(Object.X()-64,Object.X()+64), and the same with Y). To be even more sure it isn’t a close spot, but a long path, you can set a limit to the amount of steps the object can take each time (example: 12)

So you can do the code
- Pathfinding Move Object to Object.X()+RandomInRange(-64,64), Object.Y()+RandomInRange(-64,64)
- Repeat while No path found or Pathfinding:Steps>12
- Pathfinding Move Object to Object.X()+RandomInRange(-64,64), Object.Y()+RandomInRange(-64,64)

This way you can have an enemy roaming around a maze, looking for random spots to go.

Another way may be to have invisible objects that help you detect when the enemy is in a crossroad.

Be sure to test this one a couple of times, since if I recall well, the collition depends on masks sizes and may lead to enemies moving toward a wall.

This may be avoid if you line the enemies to the detection objects to be sure they will move to an open path. My best guess is to have some objects (One for each corner (4), one for each T cross (4) and one for the + cross (1)) so you can properly move the enemy.

Good luck.

Another way could be:
Make your enemies create 4 invisible blocks around it, so they can collide with the possible walls (up, down, front, back)
If the detection block is colliding with a wall, delete it.
Choose one of the random block that survived
Make enemy face said block
Move the enemy
Rinse and repeat