【问题标题】:How to move a "sprite" more smoothly in C#如何在 C# 中更顺畅地移动“精灵”
【发布时间】:2019-06-26 21:05:05
【问题描述】:

我得到了一个用 (W,A,S,D) 键移动的图片框,但它非常不稳定,你一次只能按一个键。有没有其他方法可以更顺畅地移动“精灵”?

这是我尝试过的代码:

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

【问题讨论】:

  • 我认为这是 WinForms。试图改变 UI 控件的位置会导致表单重排并且非常慢;这样你永远不会得到好的表现。如果您绝对必须使用 WinForms,请创建一个 Canvas 控件并在其中完成所有绘图。
  • WinForms 不是游戏引擎;它用于构建业务表格。如果您正在构建游戏,您可能希望使用 Unity 或类似的游戏引擎。
  • a) 移动 10 个像素是不稳定的。 b) winforms 不会将动画与显示器同步,所以它总是不均匀的。 c) 自己画,最好画在 PictureBox 或 Label 上。不要在面板上画画!在 DoubleBuffered Form 上绘图是可能的,但不容易实现增长。

标签: c# keypress


【解决方案1】:

您最好在内部更新位置,而不是通过调用 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_

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • KeyPressEventArgs.KeyChar 只能包含一个按键;他不想找别人。
    猜你喜欢
    • 1970-01-01
    • 2018-06-28
    • 2017-06-06
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多