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