更流畅的图像运动

More Fluent Image Movement

所以我四处乱逛,掌握了一些东西,我正在移动一个图片框,我已经做到了。但是,有人可以告诉我如何使运动更流畅但又不会减慢太多吗?

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace meh
{
    public partial class Form1 : Form
    {
        PictureBox Test = new PictureBox();
        public Form1()
        {
            InitializeComponent();
            FormBorderStyle = FormBorderStyle.None;
            WindowState = FormWindowState.Maximized;


           Test.Image = Properties.Resources.PlatinumGrass;
            Test.Location = new Point(0, 0);
            Test.Width = 32;
            Test.Height = 32;
            this.Controls.Add(Test);
            KeyDown += new KeyEventHandler(Form1_KeyDown);


        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            int x = Test.Location.X;
            int y = Test.Location.Y;
            int xmax = Screen.PrimaryScreen.Bounds.Width - 32;
            int ymax = Screen.PrimaryScreen.Bounds.Height - 32;
            if (e.KeyCode == Keys.Right && x < xmax ) x += 20;
            if (e.KeyCode == Keys.Left && x > 0) x -= 20;
            if (e.KeyCode == Keys.Up && y > 0) y -= 20;
            if (e.KeyCode == Keys.Down && y < ymax) y += 20;

            Test.Location = new Point(x, y);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

游戏开发建议不要使用winforms

但是您可以将这些行添加到构造函数中以进行一些改进。

SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);   

你也可以为运动部分添加一个for循环来改进它

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    int xmax = Screen.PrimaryScreen.Bounds.Width - 32;
    int ymax = Screen.PrimaryScreen.Bounds.Height - 32;

    for (int i = 0; i < 10; i++)
    {
        int x = Test.Location.X;
        int y = Test.Location.Y;
        if (e.KeyCode == Keys.Right && x < xmax) x += 2;
        if (e.KeyCode == Keys.Left && x > 0) x -= 2;
        if (e.KeyCode == Keys.Up && y > 0) y -= 2;
        if (e.KeyCode == Keys.Down && y < ymax) y += 2;
        Test.Location = new Point(x, y);
        Application.DoEvents();
    }
}