Monogame 2D top down enemy AI

1k views Asked by At

I'm trying to create a simple AI for a top down game that follows the player, but doesn't immediately take the right path to him. My enemies have to move in steps op 100 pixels before they decide to take another step. I had put together something that did what I wanted. It looked at the player's coordinates and moved towards it, but there was also a chance it took a different direction.

Now, I added multiple enemies via an EnemyManager class, and they sadly follow each others movements exactly. I'm aware this might be due to the fact that the Random function is based on the time it's executed. How can I fix this?

I am also quite sure that the method I'm using is not an efficient one:

 public void decideAImovement(Vector2 heroPosition)
 {
     Random random = new Random();
     int forwardChance = 10;
     int backChance = 10;
     int leftChance = 10;
     int rightChance = 10;

     if (position.Y > heroPosition.Y)
     {
         backChance += 50;
     }
     else if (position.Y < heroPosition.Y)
     {
         forwardChance += 50;
     }
     if (position.X > heroPosition.X)
     {
         leftChance += 50;
     }
     else if (position.X < heroPosition.X)
     {
         rightChance += 50;
     }
     backChance = random.Next(backChance);
     rightChance = random.Next(rightChance);
     leftChance = random.Next(leftChance);
     forwardChance = random.Next(forwardChance);

 int vergelijkingUD,vergelijkingLR,vergelijking;
     vergelijkingUD = Math.Max(forwardChance, backChance);
     vergelijkingLR = Math.Max(leftChance, rightChance);
     vergelijking = Math.Max(vergelijkingLR, vergelijkingUD);

     if (vergelijking == vergelijkingLR) //Left Right
     {
         if (vergelijkingLR == leftChance)
         {
             state = EnemyState.walkLeft;
         }
         else
         {
             state = EnemyState.walkRight;
         }
     }
     else //Up Down
     {
         if (vergelijkingUD == backChance)
         {
             state = EnemyState.walkBack;
         }
         else
         {
             state= EnemyState.walkForward;
         }
     }
 }

 public void moveEnemy(Vector2 heroPosition)
 {
     distanceWalked += 2;
     if (distanceWalked == gridDimensions || state == EnemyState.stop)
     {
         distanceWalked = 0;
         decideAImovement(heroPosition); 
     }

     switch (state)
     {
         case EnemyState.walkRight:
             position.X += 2.0f;
             break;
         case EnemyState.walkLeft:
             position.X -= 2.0f;
             break;
         case EnemyState.walkBack:
             position.Y -= 2.0f;
             break;
         case EnemyState.walkForward:
             position.Y += 2.0f;
             break;
         case EnemyState.stop:
             break;
     }
 }
0

There are 0 answers