Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

A Plane Game

4.00/5 (2 votes)
12 Sep 2013Ms-RL1 min read 15K   859  
A game that shows how to use C# drawing and how to create 2D anime.

 

Introduction

This is a fully functional game. The source code shows the how to use C# graphics to draw moving things. I think every developer has a dream to create a game, but when we start to do it, we don’t know how to make a start. We drag controls to simulate the plane and finally find our application flashing all the time, so here you are, the simple way of creating small games.

Background

  • Scale: the area we present our game stuff
  • Draw methods: draw line, ellipse, rectangle, image
  • Movie: when pictures keep moving, it is the movie

Using the code

The project is simple, download and build it and you will find an exe file. I added all pictures into the local resource class.

Some issues I got during development:

  1. I draw a bullet on the form, when moving it, the screen splashes all the time.
  2. Reason: if we draw a small area on the form, it will splash.

    Solution: We can draw on a BMP first, and then draw the entire BMP to our form.

    C#
    Bitmap bmp = new Bitmap(400, 400);
    Graphics g = Graphics.FromImage(bmp);
    Graphics backgroundPanel = CreateGraphics();
    backgroundPanel.DrawImage(bmp, 0F, 0F);
  3. I added the control logic in the key down event, but it has a little delay and the plane doesn’t move smoothly.

    Reason: Keyboard delay.

    Solution: When key down, we will let the plane move and there is no need to wait for the next key down. When all keys are up we will clear all moving offset.

    C#
    //In FrmMain_KeyDown event
    //
    else if (e.KeyCode == Keys.Up)
    {
       planeYOffset = -PLANE_SPEED;
       upUp = false;
    }
    else if (e.KeyCode == Keys.Down)
    {
       planeYOffset = PLANE_SPEED;
       downUp = false;
    }
    else if (e.KeyCode == Keys.Left)
    {
       planeXOffset = -PLANE_SPEED;
       leftUp = false;
    }
    else if (e.KeyCode == Keys.Right)
    {
       planeXOffset = PLANE_SPEED;
       rightUp = false;
    }
     
    //
    In FrmMain_KeyUp event
    //
    if (e.KeyCode == Keys.Up)
    {
       upUp = true;
    }
    else if (e.KeyCode == Keys.Down)
    {
       downUp = true;
    }
    else if (e.KeyCode == Keys.Left)
    {
       leftUp = true;
    }
    else if (e.KeyCode == Keys.Right)
    {
       rightUp = true;
    }
     
    if (upUp && downUp && leftUp && rightUp)
    {
       planeXOffset = 0F;
       planeYOffset = 0F;
    }

Points of Interest

Remember to abort your thread when you close the form, otherwise it will lead to an exception.

History

  • 9/11/2013: Version 1.

License

This article, along with any associated source code and files, is licensed under Microsoft Reciprocal License