I am trying to make a simple game in C # using a Visual Studio Windows Form application. I want the user to be able to freely move the blue square up, right, down and left using the appropriate keys.
I use a timer that detects a new window location every 0.1 seconds, and a keydown event that actually changes the location of the field. The box should move in the appropriate direction while the key is being held.
My problem is that my current program is doing the job, except that when the user first presses the key, the field moves a few times and pauses for a moment before it continues to move. I want to make this block smoother from the first keystroke, without stopping in this way. It can be hard to explain in words, so I added a gif file.

Is there any way to fix this? Here is my current code.
private int posX, posY;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
posY -= 3;
else if (e.KeyCode == Keys.Right)
posX += 3;
else if (e.KeyCode == Keys.Down)
posY += 3;
else if (e.KeyCode == Keys.Left)
posX -= 3;
}
private void Timer_Tick(object sender, EventArgs e)
{
Box.Location = new Point(posX, posY);
labelPosX.Text = posX.ToString();
labelPosY.Text = posY.ToString();
}
I would like to use the KeyDown event to achieve this, but if there is a better or more common way actually used in real game worlds, I would also like to know about it!
source
share