1
\$\begingroup\$

I am working on a space invaders clone using bugs as aliens. Everything works ok but the bug bitmap flickers on the screen.

    public void Form1_Load(object sender, EventArgs e)
    {

    }
    int x = 0, y = 0;
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if(e.KeyCode == Keys.Left)
        {
            x-=5;
            if(x<=-350)
            {
                x = -350;
            }
        }
        if(e.KeyCode == Keys.Right)
        {
            x+=5;
            if(x>=375)
            {
                x = 375;
            }
        }
        if (e.KeyCode == Keys.Space)
        {
            if (y <= -530)
            {
                y = 0;
            }
        }
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
        y -= 5;
        Invalidate();
    }
    protected override void OnPaintBackground(PaintEventArgs e)
    {

    }
    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        Bitmap bug_one = new Bitmap("bug_one.bmp", true);
        Bitmap ship = new Bitmap("ship.bmp", true);
        Bitmap bullet = new Bitmap("bullet.bmp", true);
        e.Graphics.Clear(this.BackColor);
        e.Graphics.DrawImage(ship, 350 + x, 530);
        e.Graphics.DrawImage(bullet, 375 + x, 520 + y);
        e.Graphics.DrawImage(bug_one, 350, 0);
        e.Graphics.Dispose();
    }
\$\endgroup\$
1
\$\begingroup\$

The best way here is to create your own double buffer. It won't completely fix the problem but will reduce it. That being drawing your entire scene to a hidden canvas then once drawing is complete you then copy that content to your front buffer or swap the canvas that your component is pointing too. Your flicker is most likely due to clearing the canvas that you can see and drawing over the top.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ I put in Doublebuffer and it worked. thanks ErnieDingo \$\endgroup\$ – gamer67 Mar 8 '19 at 20:55
  • \$\begingroup\$ @gamer67 Please consider accepting the question if it fixed your issue. \$\endgroup\$ – Vaillancourt May 12 '19 at 1:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.