The changes you are trying to make are easier to make than you might think. :)
The first thing you will need to do is change the way you determine the "velocity" of your enemies.
At the top of the Game1.cs file, find the line:
const float minEnemyVelocity = 1.0f;
Change that line of code to read
const float minEnemyVelocity = -5.0f;
Then, move down to your UpdateEnemies() method. This will be where the biggest changes are.
What you want it to do is pick a random speed between -5.0f (right to left) and 5.0f (left to right)
| public void UpdateEnemies() |
| { |
| foreach (GameObject enemy in enemies) |
| { |
| if (enemy.alive) |
| { |
| enemy.position += enemy.velocity; |
| if (!viewportRect.Contains(new Point( |
| (int)enemy.position.X, |
| (int)enemy.position.Y))) |
| { |
| enemy.alive = false; |
| } |
| } |
| else |
| { |
// This is where the changes start. Now you want your velocity first
enemy.alive = true; |
| enemy.velocity = new Vector2(MathHelper.Lerp(minEnemyVelocity, |
| maxEnemyVelocity, |
| (float)random.NextDouble()), 0); |
// You need to check which direction this enemy is going
// Less than zero is Right to Left, greater than zero is Left to Right
if (enemy.velocity.X < 0) |
| { |
| // make sure they don't travel too slowly |
| enemy.velocity.X = Math.Min(enemy.velocity.X, -1.0f); |
| // enemy travels right to left, start it at the right side |
| enemy.position = new Vector2(viewportRect.Right, |
| MathHelper.Lerp((float)viewportRect.Height * minEnemyHeight, |
| (float)viewportRect.Height * maxEnemyHeight, |
| (float)random.NextDouble())); |
| } |
| else |
| { |
| // again make sure they're not travelling too slowly this way |
| enemy.velocity.X = Math.Max(enemy.velocity.X, 1.0f); |
| // enemy travels left to right, start it at the left |
| enemy.position = new Vector2(viewportRect.Left, |
| MathHelper.Lerp((float)viewportRect.Height * minEnemyHeight, |
| (float)viewportRect.Height * maxEnemyHeight, |
| (float)random.NextDouble())); |
| } |
| } |
| } |
I hope that helps you understand the how and why of what I changed in the code. Good luck.
One final note: the MathHelper.Lerp call was changed, removing the "-" before the min and max EnemyVelocity