Enemy.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Microsoft.Xna.Framework;
  6. using Microsoft.Xna.Framework.Graphics;
  7. namespace Asteroid_Belt_Assault
  8. {
  9. class Enemy
  10. {
  11. public Sprite EnemySprite;
  12. public Vector2 gunOffset = new Vector2(25, 25);
  13. private Queue<Vector2> waypoints = new Queue<Vector2>();
  14. private Vector2 currentWaypoint = Vector2.Zero;
  15. private float speed = 120f;
  16. public bool Destroyed = false;
  17. private int enemyRadius = 15;
  18. private Vector2 previousLocation = Vector2.Zero;
  19. public Enemy(
  20. Texture2D texture,
  21. Vector2 location,
  22. Rectangle initialFrame,
  23. int frameCount)
  24. {
  25. EnemySprite = new Sprite(
  26. location,
  27. texture,
  28. initialFrame,
  29. Vector2.Zero);
  30. for (int x = 1; x < frameCount; x++)
  31. {
  32. EnemySprite.AddFrame(
  33. new Rectangle(
  34. initialFrame.X = (initialFrame.Width * x),
  35. initialFrame.Y,
  36. initialFrame.Width,
  37. initialFrame.Height));
  38. }
  39. previousLocation = location;
  40. currentWaypoint = location;
  41. EnemySprite.CollisionRadius = enemyRadius;
  42. }
  43. public void AddWaypoint(Vector2 waypoint)
  44. {
  45. waypoints.Enqueue(waypoint);
  46. }
  47. public bool WaypointReached()
  48. {
  49. if (Vector2.Distance(EnemySprite.Location, currentWaypoint) <
  50. (float)EnemySprite.Source.Width / 2)
  51. {
  52. return true;
  53. }
  54. else
  55. {
  56. return false;
  57. }
  58. }
  59. public bool IsActive()
  60. {
  61. if (Destroyed)
  62. {
  63. return false;
  64. }
  65. if (waypoints.Count > 0)
  66. {
  67. return true;
  68. }
  69. if (WaypointReached())
  70. {
  71. return false;
  72. }
  73. return true;
  74. }
  75. public void Update(GameTime gameTime)
  76. {
  77. if (IsActive())
  78. {
  79. Vector2 heading = currentWaypoint - EnemySprite.Location;
  80. if (heading != Vector2.Zero)
  81. {
  82. heading.Normalize();
  83. }
  84. heading *= speed;
  85. EnemySprite.Velocity = heading;
  86. previousLocation = EnemySprite.Location;
  87. EnemySprite.Update(gameTime);
  88. EnemySprite.Rotation =
  89. (float)Math.Atan2(
  90. EnemySprite.Location.Y - previousLocation.Y,
  91. EnemySprite.Location.X - previousLocation.X);
  92. if (WaypointReached())
  93. {
  94. if (waypoints.Count > 0)
  95. {
  96. currentWaypoint = waypoints.Dequeue();
  97. }
  98. }
  99. }
  100. }
  101. public void Draw(SpriteBatch spriteBatch)
  102. {
  103. if (IsActive())
  104. {
  105. EnemySprite.Draw(spriteBatch);
  106. }
  107. }
  108. }
  109. }