Introduction
While writing a game which I will hopefully release later on here, I had to find a way to reduce flicker. I also ran into the problem of the redraws causing the game to move extremely slow. I did some research and found out about DoubleBuffering, Timers and PaintEvents. I hope you learn from this as much as I did.
Step1: Making the Timer
- Go to the toolbar after you have made the basic WinForm skeleton. Select
Timer
and drag it to the WinForm.
- Right click on the
Timer
and hit Properties.
- Make sure that
enabled
is set to true
.
- Make the
Interval
to 1
.
- Click on the the Lightening bolt (event maker).
Step2: Make a Paint Event
Now we need to make a paint event that will draw our images for us. So we do the following:
- Include the following in the
form1()
constructor: Paint += new PaintEventHandler(OnPaint);
- Then you need to actually make the
Onpaint
event by doing the following. void OnPaint(Object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
DrawCar(g);
}
- Make a
DrawCar
function that will draw the images for us: void DrawCar(Graphics g)
{
g.DrawImage(FastCar,CarsXValue,672);
}
Step 3: Make Our Variables
Now we need some variables to control our movement. We also need an image to draw and a X co-ordinate that I will explain.
- Make the following variables where all the other main variables are declared.
int CarsXValue=0;
int CarSpeed=2;
Image FastCar=Image.FromFile("fastcar.gif");
*****Make sure the FASTCAR.GIF is in the debug or release folder**********
Step 4: Turn on Double Buffering
We now turn on double buffering to prevent flicker. Include the following code in the Form1()
constructor. And you're all set.
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.DoubleBuffer, true);
Step 5: Compile and Run
Again make sure that the fastcar.gif is in your debug or release folder depending on which build configuration you have selected.
Conclusion:
I hope this helps you as much as it did me.