using
directives to the top of the class file:using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics;
#region Declarations public Sprite EnemyBase; public Sprite EnemyClaws; public float EnemySpeed = 60f; public Vector2 currentTargetSquare; public bool Destroyed = false; private int collisionRadius = 14; #endregion
#region Constructor public Enemy( Vector2 worldLocation, Texture2D texture, Rectangle initialFrame) { EnemyBase = new Sprite( worldLocation, texture, initialFrame, Vector2.Zero); EnemyBase.CollisionRadius = collisionRadius; Rectangle turretFrame = initialFrame; turretFrame.Offset(0, initialFrame.Height); EnemyClaws = new Sprite( worldLocation, texture, turretFrame, Vector2.Zero); } #endregion
Update()
and Draw()
methods to the Enemy class:#region Public Methods public void Update(GameTime gameTime) { if (!Destroyed) { Vector2 direction = determineMoveDirection(); direction.Normalize(); EnemyBase.Velocity = direction * EnemySpeed; EnemyBase.RotateTo(direction); EnemyBase.Update(gameTime); Vector2 directionToPlayer = Player.BaseSprite.WorldCenter - EnemyBase.WorldCenter; directionToPlayer.Normalize(); EnemyClaws.WorldLocation = EnemyBase.WorldLocation; EnemyClaws.RotateTo(directionToPlayer); } } public void Draw(SpriteBatch spriteBatch) { if (!Destroyed) { EnemyBase.Draw(spriteBatch); EnemyClaws.Draw(spriteBatch); } } #endregion
The Enemy class is similar in structure to the Player class. An enemy is composed of two different Sprites that will be overlaid to create the final enemy image. Enemies move at a slightly slower speed than the player.
Between frames, each Enemy will keep track of the square it is currently trying to reach in the currentTargetSquare
vector.
When the Enemy constructor runs, the base Sprite is created using the parameters passed to the constructor, while the Sprite representing the enemy robot's claws is created by offsetting the initial frame down one row of images on the sprite sheet.
Both the Update()
and the Draw()
methods only take action if the enemy has not been destroyed. During Update()
, the determineMoveDirection()
method (which we have not yet written) is called. The job of this method will be to return a vector representing the direction that the enemy should be moving in during this frame.
Given that information, the Enemy is moved in the same way that the Player is moved. The EnemyBase
Sprite is rotated to the direction of movement, and its velocity is set taking the EnemySpeed
variable into account.
When the EnemyClaws
Sprite is updated, it is rotated to face the player's current position, resulting in the enemy always reaching for the player.
18.218.156.35