【发布时间】:2019-07-15 10:35:19
【问题描述】:
我想使用计时器自动移动一个按钮,并希望它在按下另一个键时改变方向,有点像蛇中发生的事情
我使用了一个字符串来设置方向,但这不起作用。
字符串 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;
}
}
}
按钮刚刚消失,但我希望它移动 10 直到它得到一个像“D”这样的按键然后它改变方向
【问题讨论】:
-
尝试使用 Location 属性。
Player.Loaction = new Point(x, y) -
你是这个意思吗? while (x == "up") { Player.Location = new Point(Y += 10); }
-
不要在 Tick 事件处理程序中使用 while(),这将是一个非常短的游戏。使用 if()。并添加“游戏结束”检查。
-
如果您将 X="right" 设置为默认计时器,它将在玩家开始行动之前将其移动。因此,如果 x 为空,则返回条件