首页 > 解决方案 > 如何使用计时器和按键事件移动对象(如蛇)

问题描述

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

我使用了一个字符串来设置方向应该是什么,但这不起作用。

字符串 x = "对";

    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”这样的按键,然后它改变方向

标签: c#winforms

解决方案


1:您每次都在本地创建变量“x”意味着在 player_keyDown 事件中,因此全局创建它。

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

3:代替顶部,左侧使用按钮的位置属性,它为您提供 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);
        }

    }

}

推荐阅读