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:
- I draw a bullet on the form, when moving it, the screen splashes all the time.
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.
Bitmap bmp = new Bitmap(400, 400);
Graphics g = Graphics.FromImage(bmp);
Graphics backgroundPanel = CreateGraphics();
backgroundPanel.DrawImage(bmp, 0F, 0F);
- 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.
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