我有一个程序,我想用键盘键移动一个Graphic。我最初有一个功能,只要按下一个按钮就可以移动图形,但我放弃了这种方法来绕过键盘重复延迟。相反,我决定使用一个计时器,我将在KeyPess事件上启用它,并禁用KeyUp事件。起初,我为每个不同的方向使用了4个不同的计时器,虽然它有效但我注意到我的程序已经开始经常冻结。我决定对所有动作使用单个计时器,并使用if语句来确定方向。现在,似乎我的Graphic根本没有移动,即使我所做的只是复制和粘贴代码。
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();
}
什么阻止我的图形移动,有没有更好的方法来做到这一点?我还想添加很多功能,但它已经冻结了。
答案 0 :(得分:1)
不确定您是否正在使用WinForms制作游戏,但重点是......
您需要处理按键事件,当按下按键事件时,根据事件是按下还是释放,在代码中设置一个布尔标记。然后在更新代码中检查标记并相应地进行移动。
这将是这样的(示例代码):
bool moveup = false;
void KeyPressed(object sender, KeyEventArgs e)
{
// check for keys that trigger starting of movement
if (e.KeyCode == Keys.W) moveup = true;
}
void KeyReleased(object sender, EventEventArgs e)
{
// check for keys that trigger stopping of movement
if (e.KeyCode == Keys.W) moveup = false;
}
void TimerTick(obect sender, EventArgs e)
{
if (moveup)
{
// move your object
}
}