Reputation: 821
I have a problem that I'm struggling with.. I want to move an image using my keyboard to the left, right, up or down and in a diagonal way. I searched the web and found, that to use 2 diffrent keys I need to remember the previous key, so for that I'm using a bool dictionary.
in my main Form class this is how the KeyDown event looks like:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
baseCar.carAccelerate(e.KeyCode.ToString().ToLower());
carBox.Refresh(); //carbox is a picturebox in my form that store the image I want to move.
}
My KeyUp event:
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
baseCar.carBreak(e.KeyCode.ToString().ToLower());
}
My Paint event:
private void carBox_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(Car, baseCar.CharPosX, baseCar.CharPosY); // Car is just an image
}
And my baseCar class:
private Dictionary KeysD = new Dictionary(); // there is a method to set the W|A|S|D Keys, like: KeysD.Add("w",false)
public void carAccelerate(string moveDir)
{
KeysD[moveDir] = true;
moveBeta();
}
public void moveBeta()
{
if (KeysD["w"])
{
this.CharPosY -= this.carMoveYSpeed;
}
if (KeysD["s"])
{
CharPosY += carMoveYSpeed;
}
if (KeysD["a"])
{
CharPosX -= carMoveXSpeed;
}
if (KeysD["d"])
{
CharPosX += carMoveXSpeed;
}
}
public void carBreak(string str)
{
KeysD[str] = false;
}
Anyway it works, but my problem is that I can't get back to the first pressed key for example:
I pressed W to move up and then the D key to go diagonal, how ever when I release the D key it wont go Up again because the KeyDown event is "dead" and wont call the carAccelerate() method again.. and I can't figure out how to fix it..
Can any one help me please? Maybe there is a better way to handle the keys? im open to any ideas! And I hope you can understand it, my english isnt the best :S
Upvotes: 0
Views: 1197
Reputation: 151594
Store all keystates and don't animate on keypress, but for example using a timer.
Then:
KeyDown(key)
{
KeyState[key] = true;
}
KeyUp(key)
{
KeyState[key] = false;
}
Timer_Tick()
{
Animate();
}
Animate()
{
if (KeyState["W"])
{
// Accelerate
}
if (KeyState["S"])
{
// Decelerate
}
}
Then in the KeyDown
method you can check for conflicting keys (what if accelerate + decelerate are pressed at the same time, and so on).
Upvotes: 1