using
directives to the top of the class file:using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics;
static class EnemyManager
#region Declarations public static List<Enemy> Enemies = new List<Enemy>(); public static Texture2D enemyTexture; public static Rectangle enemyInitialFrame; public static int MaxActiveEnemies = 30; #endregion
Initialize()
method to the EnemyManager class:#region Initialization public static void Initialize( Texture2D texture, Rectangle initialFrame) { enemyTexture = texture; enemyInitialFrame = initialFrame; } #endregion
AddEnemy()
method to the EnemyManager class:#region Enemy Management public static void AddEnemy(Vector2 squareLocation) { int startX = (int)squareLocation.X; int startY = (int)squareLocation.Y; Rectangle squareRect = TileMap.SquareWorldRectangle(startX, startY); Enemy newEnemy = new Enemy( new Vector2(squareRect.X, squareRect.Y), enemyTexture, enemyInitialFrame); newEnemy.currentTargetSquare = squareLocation; Enemies.Add(newEnemy); } #endregion
Update()
and Draw()
methods to the EnemyManager Class:#region Update and Draw EnemyManager classEnemyManager classupdatingpublic static void Update(GameTime gameTime) { for (int x = Enemies.Count - 1; x >= 0; x--) { Enemies[x].Update(gameTime); if (Enemies[x].Destroyed) { Enemies.RemoveAt(x); } } } public static void Draw(SpriteBatch spriteBatch) { foreach (Enemy enemy in Enemies) { enemy.Draw(spriteBatch); } } #endregion
Update()
method with the following:public void Update(GameTime gameTime) { if (Active) { float elapsed = (float)gameTime.ElapsedGameTime. TotalSeconds; LastSpawnCounter += elapsed; if (LastSpawnCounter > minSpawnTime) { if (Vector2.Distance(activeSprite.WorldCenter, Player.BaseSprite.WorldCenter) > 128) { if (EnemyManager.Enemies.Count < EnemyManager.MaxActiveEnemies) { EnemyManager.AddEnemy(MapLocation); LastSpawnCounter = 0; } } } activeSprite.Update(gameTime); } else { inactiveSprite.Update(gameTime); } }
LoadContent()
method of the Game1 class, initialize the EnemyManager:EnemyManager.Initialize( spriteSheet, new Rectangle(0, 160, 32, 32));
Update()
method of the Game1 class, update the EnemyManager right after the GoalManager had been updated:EnemyManager.Update(gameTime);
Draw()
method of the Game1 class, draw the EnemyManager right after the GoalManager has been drawn:EnemyManager.Draw(spriteBatch);
Most of the EnemyManager class is standard for our managers. When an enemy is added via the AddEnemy()
method, the enemy's currentTargetSquare
member is set to the square that the enemy has been spawned in, meaning that on its first Update()
cycle, it will execute PathFinder.FindPath()
to determine a path towards the player.
3.21.100.34