28. Ghosts in all directions
Now our ghost check collisions with the walls and return in the opposite direction when they find an obstacle.
Making them move in random directions is not difficult: we were doing this:
// Move enemies and environment for (int i = 0; i < amountOfEnemies; i++) { if (CanMoveTo((int)(enemies[i].x + enemies[i].xSpeed), (int)enemies[i].y, map)) enemies[i].x += enemies[i].xSpeed; else enemies[i].xSpeed = -enemies[i].xSpeed; }
And now we would pick a random number from 0 to 3, meaning the next direction in which the ghost will try to move:
for (int i = 0; i < amountOfEnemies; i++) { if (CanMoveTo((int)(enemies[i].x + enemies[i].xSpeed), (int)(enemies[i].y + enemies[i].ySpeed), map)) { enemies[i].x += enemies[i].xSpeed; enemies[i].y += enemies[i].ySpeed; } else { switch (randomGenerator.Next(0, 4)) { case 0: // Next move: to the right enemies[i].xSpeed = 4; enemies[i].ySpeed = 0; break; case 1: // Next move: to the left enemies[i].xSpeed = -4; enemies[i].ySpeed = 0; break; case 2: // Next move: upwards enemies[i].xSpeed = 0; enemies[i].ySpeed = -4; break; case 3: // Next move: downwards enemies[i].xSpeed = 0; enemies[i].ySpeed = 4; break; } } }
We only need to declare that "randomGenerator" as a "Random" variable in the beggining of our program:
static Random randomGenerator;
And initialize it in our "Init" function:
randomGenerator = new Random();
We have made few changes, so there will be no full source this time.