Reputation: 9
I want to program a little game in C#. At the moment there are only squares involved, but I'll come to the details later on.
So there is a lot of stuff going on in the background, like collision detecting, bullet movement, player movement, focusing with the "camera" on the player (and enemy AI in the future). To execute all these tasks I have a timer with an intervall of 10 milliseconds. With each tick, physics "happen" and the screen will be redrawn.
Now to the problem: The screen is flickering,... not that bad but I think it will be worse when I add more things. I've tried to draw to image offscreen and draw it afterwards, as a whole image to the screen. But I need to create several Bitmap and Graphics objects, and after about 30 seconds the program will use like 2GB of RAM.
public void Draw()
{
Bitmap bmpMap = new Bitmap(Map.Width, Map.Height);
Graphics gphMap = Graphics.FromImage(bmpMap);
Bitmap bmpWeapon = new Bitmap(WeaponSector.Width, WeaponSector.Height);
Graphics gphWeapon = Graphics.FromImage(bmpWeapon);
DrawMap(gphMap);
DrawWeaponSector(gphWeapon);
Map.CreateGraphics().DrawImage(bmpMap, 0, 0);
gphMap.Dispose();
WeaponSector.CreateGraphics().DrawImage(bmpWeapon, 0, 0);
gphWeapon.Dispose();
}
Note: I don't draw directly on the form, but in Panels. They are called Map (here is the action going on) and WeaponSector (here you can see your current weapon and ammo).
Upvotes: 1
Views: 1918
Reputation: 1598
Be sure to use double buffering for the form:
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
http://msdn.microsoft.com/en-us/library/system.windows.forms.controlstyles.aspx
Upvotes: 0
Reputation: 11209
Create two bitmap objects and their graphic objects once and store them. Call your Draw method passing the graphic objects. That way, you will avoid to wait for the GC to garbage collect the bitmap objects at a rate of 30 fps minimum.
Upvotes: 2