3. Enemy Class
The AlienGameObject class that represents the frenzied aliens is remarkably simple. The class inherits from the GameObject class and uses the inherited constructor with some modifications:
public AlienGameObject(SpriteSheet loadedTexture,
string spriteName, Rectangle screenRect)
: base(loadedTexture, spriteName, screenRect)
{
Alive = true;
ResetGameObject();
}
The Alive property is set to true because we want enemies to keep dropping. There is a customized ResetGameObject method that overrides the base class version as well:
public override void ResetGameObject()
{
//Randomize animation
_spriteIndex = (int)(randomNumber.NextDouble() * NumberOfAnimationFrames);
//Randomize initial position
Position = new Vector2(randomNumber.Next(_screenRect.Width), 35);
//Apply default alien speed
Velocity = new Vector2(randomNumber.Next(alienVelocityArc), alienSpeed);
Alive = true;
}
The alien spaceship has a unique shape. For better collision detection we override the BoundingRect property and call Rectangle.Inflate(0,2); to inflate the Rectangle on the Y axis resulting in much better collision detection for this game:
public override Rectangle BoundingRect
{
get
{
Rectangle rect = new Rectangle((int)Position.X, (int)Position.Y,
SpriteAnimationSpriteSheet.SourceRectangle(SpriteName + 0).Width,
SpriteAnimationSpriteSheet.SourceRectangle(SpriteName + 0).Height);
rect.Inflate(0,20);
return rect ;
}
}
That's it to this class. All of the lively action is a result of the animation code handled by the base class and the ResetGameObject method. The ResetGameObject method does a couple of things:
It starts the animation at a random index, so that the objects don't appear to be animating in sync, which would be boring.
It randomly picks an 'X' value for the initial PositionVector2 to start the drop.
Finally,
it applies a random but very small 'X' value to the Velocity so that
the alien space ships don't appear to just fall straight down.
Figure 5 shows an army of aliens invading.
You will want to play on a real device to get a full sense of the game, but as you can see in Figure 5,
the aliens strike different drop lines and fall fairly randomly for
such little code. The animation code helps to keep things lively as
well. In the next section, we cover the hero ship class, which takes
accelerometer and touch input to move and fire missiles at the invasion.