想要实现“按住AD能够使角色持续性的左右移动”的功能,自己写的代码如下:
private void Character_KeyDown(object sender, KeyEventArgs e)
{
int x = 0, y = 335;
pictureBox1.Location = new System.Drawing.Point(x, y);
switch (e.KeyCode)
{
case Keys.A:
x = x - 20;
pictureBox1.Location = new System.Drawing.Point(x, y);
break;
case Keys.D:
x = x + 20;
pictureBox1.Location = new System.Drawing.Point(x, y);
break;
}
}
目前的问题是按下“D”后picturebox向右移动一个单位,再按“D”就不会动了,同时按住“D”picturebox也不会移动,还会闪一下。
窗体里只有一个pixtureBox的控件
想知道该怎么实现功能,以及是代码的问题还是控件属性设置问题。
//先给窗体添加Timer控件,假设你的name为timer1
private bool _isleft;
private int x = 0;
private int y = 335;
private void timer1_Tick(object sender, EventArgs e)
{
if (_isleft)
{
x = x - 20;
pictureBox1.Location = new System.Drawing.Point(x, y);
}
else
{
x = x + 20;
pictureBox1.Location = new System.Drawing.Point(x, y);
}
}
private void Character_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.A:
_isleft = true;
timer1.Interval = 50;//计时器的代码,每50毫秒也就是0.05s运行一次,自行调整
timer1.Enabled = true;
break;
case Keys.D:
_isleft = false;
timer1.Interval = 50;//计时器的代码,每50毫秒也就是0.05s运行一次,自行调整
timer1.Enabled = true;
break;
}
}
private void Character_KeyUp(object sender, KeyEventArgs e)
{
timer1.Enable = false;
}
没有看到你重新绘制图片的方法,改变了坐标,需要重新绘制图片才行吧。
用Timer
int x = 0, y = 335; 两个变量提到 方法 private void Character_KeyDown(object sender, KeyEventArgs e) 外面