Search code examples
c#keypress

How to move a "sprite" more smoothly in C#


I have gotten a Picturebox to move with (W,A,S,D) keys but it is very choppy and you can only press on key at a time. Is it any other way you can move a "sprite" more smoothly?

This is my code i have tried:

    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        int offset = 10;
        if (e.KeyChar == 'a')
        {
            pictureBox1.Location = new Point(pictureBox1.Location.X - offset, pictureBox1.Location.Y);
        }
        else if (e.KeyChar == 'w')
        {
            pictureBox1.Location = new Point(pictureBox1.Location.X, pictureBox1.Location.Y - offset);
        }
        else if (e.KeyChar == 's')
        {
            pictureBox1.Location = new Point(pictureBox1.Location.X, pictureBox1.Location.Y + offset);
        }
        else if (e.KeyChar == 'd')
        {
            pictureBox1.Location = new Point(pictureBox1.Location.X + offset, pictureBox1.Location.Y);
        }
    }

Solution

  • You might be better off updating the location internally instead of assigning it a new value by calling pictureBox1.Location.Translate(offset, offset);

    See https://learn.microsoft.com/en-us/dotnet/api/system.drawing.point.offset?view=netframework-4.8#System_Drawing_Point_Offset_System_Int32_System_Int32_