如何在 C# 中更平滑地移动 "sprite"

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

我得到了一个用 (W,A,S,D) 键移动的 Picturebox,但它非常不稳定,您一次只能按一个键。有没有其他方法可以更顺畅地移动 "sprite"?

这是我试过的代码:

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

您最好在内部更新位置,而不是通过调用 pictureBox1.Location.Translate(offset, offset);

为其分配新值

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

要扩展 Babak 并回答您的另一部分(一次只按一个键),请将您的 else if 更改为仅一系列 if 语句。使用 else if,只要其中一个为真,它就会中断序列,这意味着一旦您按下一个键,它就不会寻找其他键。