如何使用计时器和按键事件移动对象(如蛇)

时间:2019-07-15 10:35:19

标签: c# winforms

我想使用计时器自动移动按钮,并希望在按下另一个键时改变方向,就像在蛇中发生的一样

我使用了一个字符串来设置方向,但这是行不通的。

string x =“ right”;

    public Form1()
    {
        InitializeComponent();
        timer1.Interval = 1000;
        timer1.Start();

    }

    private void Player_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.W)
        {
            string x = "up";
        }
        else if (e.KeyCode == Keys.S)
        {
            string x = "down";
        }
        else if (e.KeyCode == Keys.D)
        {
            string x = "right";
        }
        else if (e.KeyCode == Keys.A)
        {
            string x = "left";
        }

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void Timer1_Tick(object sender, EventArgs e)
    {
        while (x == "up")
        {
            Player.Top -= 10;
        }
        while (x == "down")
        {
            Player.Top += 10;
        }
        while (x == "right")
        {
            Player.Left += 10;
        }
        while (x == "left")
        {
            Player.Left -= 10;
        }
    }
}

按钮只是消失了,但是我希望它移动十个直到它被按下,例如“ D”,然后它改变方向

1 个答案:

答案 0 :(得分:1)

1:您每次在player_keyDown事件中均在本地创建变量'x'时,请全局创建该变量。

2:您正在使用while循环,不需要,因为您已经在使用timer_tick。

3:代替顶部,左侧使用按钮的Location属性,它为您提供X,Y坐标

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
        timer1.Interval = 1000;
        timer1.Start();
    }

    string x = "right";
    private void Player_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.W)
        {
            x = "up";
        }
        else if (e.KeyCode == Keys.S)
        {
            x = "down";
        }
        else if (e.KeyCode == Keys.D)
        {
            x = "right";
        }
        else if (e.KeyCode == Keys.A)
        {
            x = "left";
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {

        if (x == "up")
        {
            Player.Location = new System.Drawing.Point(Player.Location.X, Player.Location.Y - 10);
        }
        if (x == "down")
        {
            Player.Location = new System.Drawing.Point(Player.Location.X, Player.Location.Y + 10);
        }
        if (x == "right")
        {
            Player.Location = new System.Drawing.Point(Player.Location.X + 10, Player.Location.Y);
        }
        if (x == "left")
        {
            Player.Location = new System.Drawing.Point(Player.Location.X - 10, Player.Location.Y);
        }

    }

}