简体   繁体   中英

How to optimize Form repaint

Trying to write a simple 2D game. Done this:

public interface GameObject
{
    Bitmap Picture  { get; }
    int OffsetX     { get; }
    int OffsetY     { get; }
}

Here Picture property returns a picture that should be drawn for this current object.

public static class Game
{
    public class MapIndexer
    {
        public GameObject this[int x, int y]
        {
            get => map[y, x];
            set => map[y, x] = value;
        }
    }

    private static MapIndexer indexer;
    public static MapIndexer Map
    {
        get => indexer ?? (indexer = new MapIndexer());
    }

    static GameObject[,] map = new GameObject[,]
    {
        { null, null, null },
        { null, null, null },
        { null, null, null }
    };

    public static int MapWidth
    {
        get => map.GetLength(1);
    }
    public static int MapHeight
    {
        get => map.GetLength(0);
    }
}

A Game class that contains Map indexer and for further development. [y, x] indexing is to access Map like Cartesian coords, otherwise I get inverted dimensions. NULL in array is just a filler (ie grass in my game, it does nothing and just needed to fill the map, so I see no reason to create a separate class for it). Also created a simple Player class from GameObject interface which just returns a Picture to be drawn. And here is actual paint code:

private void Form1_Paint(object sender, PaintEventArgs e)
{
    for (int y = 0; y < Game.MapHeight; y++)
        for (int x = 0; x < Game.MapWidth; x++)
        {
            e.Graphics.DrawImage(Properties.Resources.Grass, new Point(x * size, y * size));
            if (Game.Map[x, y] is not null)
                e.Graphics.DrawImage(Game.Map[x, y].Picture, new Point(x * size + Game.Map[x, y].OffsetX, y * size + Game.Map[x, y].OffsetY));
        }
}

So when I do some move, I invalidate a form and get next frame. It looks weird for me, actually it is because when action is performed, the picture flashes each redraw operation. The animation for test is player move, which occurs every 200ms, which isn't much. So the question is: how to optimise drawing so it can look smooth, or my code design is actually bad at start?

The effect you are experiencing is not really related to performance. What you are seeing, is most likely the effect of clearing the screen before the redraw. You should look into a concept called "double buffering".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM