How can I get an NPC to move randomly in XNA?
- by Fishwaffles
I basically want a character to walk in one direction for a while, stop, then go in another random direction. Right now my sprites look but don't move, randomly very quickly in all directions then wait and have another seizure. I will post the code I have so far in case that is useful.
class NPC: Mover
{
int movementTimer = 0;
public override Vector2 direction
{
get
{
Random rand = new Random();
int randDirection = rand.Next(8);
Vector2 inputDirection = Vector2.Zero;
if (movementTimer >= 50)
{
if (randDirection == 4)
{
inputDirection.X -= 1;
movingLeft = true;
}
else movingLeft = false;
if (randDirection == 1)
{
inputDirection.X += 1;
movingRight = true;
}
else movingRight = false;
if (randDirection == 2)
{
inputDirection.Y -= 1;
movingUp = true;
}
else movingUp = false;
if (randDirection == 3)
{
inputDirection.Y += 25;
movingDown = true;
}
else movingDown = false;
if (movementTimer >= 100)
{
movementTimer = 0;
}
}
return inputDirection * speed;
}
}
public NPC(Texture2D textureImage, Vector2 position,
Point frameSize, int collisionOffset, Point currentFrame, Point sheetSize,
Vector2 speed)
: base(textureImage, position, frameSize, collisionOffset, currentFrame,
sheetSize, speed)
{
}
public NPC(Texture2D textureImage, Vector2 position,
Point frameSize, int collisionOffset, Point currentFrame, Point sheetSize,
Vector2 speed, int millisecondsPerframe)
: base(textureImage, position, frameSize, collisionOffset, currentFrame,
sheetSize, speed, millisecondsPerframe)
{
}
public override void Update(GameTime gameTime, Rectangle clientBounds)
{
movementTimer++;
position += direction;
if (position.X < 0)
position.X = 0;
if (position.Y < 0)
position.Y = 0;
if (position.X > clientBounds.Width - frameSize.X)
position.X = clientBounds.Width - frameSize.X;
if (position.Y > clientBounds.Height - frameSize.Y)
position.Y = clientBounds.Height - frameSize.Y;
base.Update(gameTime, clientBounds);
}
}