Using C# and the Monogame framework, I remade a popular arcade game called 1945. The game is an endless runner, high-score game. My objective was to learn how to spawn enemies and how to shoot. I also learn odd shaped collision detection. Since the plane is not a perfect rectangle, I had to put a collision rectangle around the body and another around the wings.
Above is the enemy collsion rectangles. This makes a more accurate collision between the bullet and enemy.
First I made two variables I would need. Two rectangles for the body and the wings.
public RectanglecollisionRectHorizontal, collisionRectVertical;
Then I initialized the values to the current position where the enemy is spawned.
public Enemy(Rectangle clientBounds, string color)
{
...
this.collisionRectHorizontal = new Rectangle((int)position.X, (int)position.Y, frameWidth, 7);
this.collisionRectVertical = new Rectangle((int)position.X + 8, (int)position.Y, 4, frameWidth);
this.color = color;
}
Next, I needed to load the sprite sheet, this loads whatever color enemy I set in the constructor.
public void Load(ContentManager cm)
{
tile = cm.Load<Texture2D>("Sprites/enemies/"+color);
}
After than, I wrote the update method. This changes the current frame of the sprite to make the enemies perpeller look like it is spinning. The method also updates the source and collision rectangles to the current position of the enemy.
public void Update(GameTime gameTime)
{
elapsed += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if (elapsed >= delay)
{
if (frame >= 1)
{
frame = 0;
}
else
{
frame++;
}
elapsed = 0;
}
position.Y++;
sourceRect = new Rectangle(frameWidth * frame + frame + 1, 1, frameWidth, frameWidth);
collisionRectHorizontal = new Rectangle((int)position.X, (int)position.Y + frameWidth/2, frameWidth, 7);
collisionRectVertical = new Rectangle((int)position.X + 7, (int)position.Y, 7, frameWidth + 1);
}
Finally, I draw the enemy to the screen.
public void Draw(SpriteBatch sb)
{
sb.Draw(sprite, position, sourceRect, Color.White);
}