Time for action - creating the Enemy class

  1. Add a new class called Enemy to the Asteroid Belt Assault project.
  2. Add the standard using directives to the class:
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Graphics;
    
  3. Add declarations to the Enemy class:
    public Sprite EnemySprite;
    public Vector2 gunOffset = new Vector2(25, 25);
    private Queue<Vector2> waypoints = new Queue<Vector2>();
    private Vector2 currentWaypoint = Vector2.Zero;
    private float speed = 120f;
    public bool Destroyed = false;
    private int enemyRadius = 15;
    private Vector2 previousLocation = Vector2.Zero;
    
  4. Add a constructor to the Enemy class:
    public Enemy(
    Texture2D texture,
    Vector2 location,
    Rectangle initialFrame,
    int frameCount)
    {
    EnemySprite = new Sprite(
    location,
    texture,
    initialFrame,
    Vector2.Zero);
    for (int x = 1; x < frameCount; x++)
    {
    EnemySprite.AddFrame(
    new Rectangle(
    initialFrame.X = (initialFrame.Width * x),
    initialFrame.Y,
    initialFrame.Width,
    initialFrame.Height));
    }
    previousLocation = location;
    currentWaypoint = location;
    EnemySprite.CollisionRadius = enemyRadius;
    }
    

What just happened?

As always, our object contains a Sprite object that will provide its base display and update capabilities. Just like we did with the player ship, we have included a vector pointing to the location on the sprite where shots will begin when the enemy ship fires its cannon.

Enemy ships will be supplied with a list of waypoints that they will progress through, with the waypoint the ship is currently attempting to reach stored in the currentWaypoint variable. Movement towards the current waypoint will be scaled by speed.

When the Sprite representing the enemy is created, the enemyRadius value will be copied to the Sprite's CollisionRadius member for checking during collision detection.

The Destroyed Boolean will be set to true by the CollisionManager class we will create in Chapter 5. When Destroyed is true, the ship will not be drawn, updated, or eligible for collision with other objects.

In order to rotate the enemy ship automatically to point in the direction it is travelling, the previousLocation vector stores the ship's location during the previous frame. By calculating the vector from the previous location to the new location, we can determine the facing of the ship and rotate the image appropriately.

Most of the Enemy constructor simply initializes a new Sprite object with the passed parameters, adding frames to the sprite based on frameCount. Both the previousLocation and the currentWaypoint values are set to the sprite's creation position, and the collision radius is set at the end of the constructor.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.29.219