简体   繁体   中英

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);
        }
    }

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://docs.microsoft.com/en-us/dotnet/api/system.drawing.point.offset?view=netframework-4.8#System_Drawing_Point_Offset_System_Int32_System_Int32_

To extend off of Babak and answer your other part (only pressing one key at a time), change your else if to just a series of if statements. With else if, it breaks out of the sequence as soon as one of them is true, meaning that once you press one key, it doesn't look for the others.

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