c# - 如何使用计时器和按键事件移动对象(如蛇)
问题描述
我想使用计时器自动移动一个按钮,并希望它在按下另一个键时改变方向,有点像蛇中发生的事情
我使用了一个字符串来设置方向应该是什么,但这不起作用。
字符串 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”这样的按键,然后它改变方向
解决方案
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);
}
}
}
推荐阅读
- html - 如果我们将字符集定义为 utf-8,那么 HTML 中的 lang 属性有什么用
- amazon-web-services - AWS SSO - 您的请求包含无效的 SAML 响应
- sql-server - 如何在 SQL Server 级别启用 Identity_insert
- python - 我如何使用 apache 访问 django?apache在django上显示默认页面
- r - flextable 和 officedown 错误:read_docx 仅支持 docx 文件
- javascript - TypeError:text.select 不是函数
- r - 在r中将数据从一个数据帧提取到另一个数据帧
- php - 在订单管理页面 WooCommerce 中编辑元数据
- image - Xamarin:将下载的图像从页面传递到另一个页面
- google-cloud-platform - 由于有关 Cloud SQL 联合连接不在“查询区域”中的 BigQuery 警告消息,GCP 数据流失败