0
我有一个程序,我想用键盘按键移动图形。我原本有一个功能来移动图形,只要按下按钮,但我放弃了这种方法来解决键盘重复延迟问题。相反,我决定使用计时器,在KeyPess事件中启用该计时器,并在KeyUp事件中禁用该计时器。起初,我为每个不同的方向使用了4个不同的定时器,虽然它起作用,但我注意到我的程序经常开始冻结。我决定为所有动作使用一个计时器,并使用if语句来确定方向。现在,看起来我的图形根本不动,尽管我所做的只是复制和粘贴代码。为什么我的物体不移动?
enum Direction
{
Left, Right, Up, Down
}
private Direction _objectDirection;
int _x = 100, _y = 100;
private void Form1_Paint(object sender, PaintEventArgs e)
{
Picture.MakeTransparent(Color.Transparent);
e.Graphics.DrawImage(Picture, _x, _y);
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
if (timerAnimation.Enabled == false)
{
AnimationMaxFrame = 3;
timerAnimation.Enabled = true;
}
_objectDirection = Direction.Up;
timerMovement.Enabled = true;
}
//The rest of this code is omitted to save space, it is repeated 4 times with the only
//changes being the key pressed, and the object direction.
Invalidate();
}
void Form1_KeyUp(object sender, KeyEventArgs e)
{
timerAnimation.Enabled = false;
timerMovement.Enabled = false;
Picture = Idle;
this.Refresh();
}
private void timerMovement_Tick(object sender, EventArgs e)
{
if (_objectDirection == Direction.Up)
{
if (_y > 24)
{ _y = _y - 2; }
else
{ timerMovement.Enabled = false; }
//This if statement is to ensure that the object doesn't leave the form.
//I have tried removing them already, they're not the problem.
}
//Again, this is shortened to save space, it is repeated for each direction.
Invalidate();
}
什么是阻止我的图形移动,有没有更好的方法来做到这一点?我还想添加很多功能,但它已经冻结了。
为什么你有两个定时器? –
其中一个定时器是动画,另一个是动作。 – user3303233