Renet
Renet

Reputation: 349

Random enemy movement direction

I'm working on a top-down shooter and I want my enemies to wander around aimlessly. In this code I have an Enemy class with all the variables(rotation,position, etc) including the random(rnd) in the main class.

My problem is that the enemies keep moving from the top right corner of the screen to the bottom left. So they are not wandering around, but always get a certain direction. I would like to know why is that so.

refresh += gameTime.ElapsedGameTime.TotalSeconds;

if (refresh >= 3)
{
    refresh -= 3;
    int rndDirection = rnd.Next(4);

    if (rndDirection == 1) vektor = new Vector2(0, -1);
    if (rndDirection == 2) vektor = new Vector2(0, 1);
    if (rndDirection == 3) vektor = new Vector2(1, 0);
    if (rndDirection == 4) vektor = new Vector2(-1, 0);

    foreach (Enemy enemy in enemies)
    {
        Vector2 rndDirVec = vektor;
        enemy.directionX = enemy.position.X - rndDirVec.X;
        enemy.directionY = enemy.position.Y + rndDirVec.Y;
        enemy.rotation = (float)Math.Atan2(enemy.directionY, enemy.directionX);
    }
}
foreach (Enemy enemy in enemies) 
    {
        enemy.position -= new Vector2((float)(enemy.speed/2 *   Math.Cos(enemy.rotation)), (float)(enemy.speed/2 * Math.Sin(enemy.rotation)));
    }

I'm fairly new to C# so I might lack some knowledge of how things function in it, so could someone point me in a right direction perhaps?

Upvotes: 0

Views: 5096

Answers (2)

kol
kol

Reputation: 28688

The integer argument of Random.Next is an exclusive upper bound, so rndDirection will be 0, 1, 2, or 3. You never increase the X coordinate, so the enemies will always go left.

I would do something like this (I never used XNA, and I don't know the details of your code, so I'm not sure this is 100% correct):

foreach (Enemy enemy in enemies)
{
  enemy.direction.X = rnd.Next(3) - 1; // -1, 0, +1
  enemy.direction.Y = rnd.Next(3) - 1; // -1, 0, +1
  Vector2 movement = Vector2.Multiply(enemy.direction, enemy.speed);
  enemy.position = Vector2.Add(enemy.position, movement);
}

Or, if you want finer direction changes:

const float rotationStep = 5.0f * Math.PI / 180.0f; // 5 degrees
foreach (Enemy enemy in enemies)
{
  enemy.rotation += (rnd.Next(3) - 1) * rotationStep;
  enemy.direction.X = Math.Cos(enemy.rotation);
  enemy.direction.Y = Math.Sin(enemy.rotation);
  Vector2 movement = Vector2.Multiply(enemy.direction, enemy.speed);
  enemy.position = Vector2.Add(enemy.position, movement);
}

Upvotes: 5

Jay
Jay

Reputation: 303

the argument for rand.next is an upper bound, also unless you want all of your enemies to always move together I would recalculate the random vector inside of the foreach loop for enemies so they each get a random movement instead of all performing the same random movement (unless thats what you want).

Upvotes: 1

Related Questions