Removing the delay after KeyDown event? - c#

When I hold a key in my game to move my player:
public void MainForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
Player.MoveUp();
}
}
The player instantly moves one step as soon as I press the down arrow, and then pauses for a short duration before starting to smoothly move again. Why's this? How can I prevent it?

The answer in the proposed duplicate is incorrect, unfortunately. It doesn't ignore repeated KeyDown events, and so will gradually increase the "delta" value in the direction being handled by each key case. It also doesn't respond to the keypress immediately (i.e. no action happens until the first timer tick).
This answer to Holding Arrow Keys Down For Character Movement C# .Net ISSUES explains how to ignore the subsequent KeyDown events, but doesn't explain how then your character would move.
In other words, I couldn't find a duplicate question that actually correctly answers your question. So…
The basic technique you want to do is:
Don't move on the actual key input. Instead, generate your own timing logic that will move the object.
Instead of using the KeyDown event to actually move the object, use it to set a movement direction, which is then processed by your timing logic.
There are a variety of ways to accomplish this. One version would look like this:
private bool _moveUp;
private bool _moveDown;
private bool _moveLeft;
private bool _moveRight;
// You can add the Timer in the Winforms Designer instead if you like;
// The Interval property can be configured there at the same time, along
// with the Tick event handler, simplifying the non-Designer code here.
private System.Windows.Forms.Timer _movementTimer = new Timer { Interval = 100 };
public MainForm()
{
InitializeComponent();
_movementTimer.Tick += movementTimer_Tick;
}
private void movementTimer_Tick(object sender, EventArgs e)
{
_DoMovement();
}
private void _DoMovement()
{
if (_moveLeft) Player.MoveLeft();
if (_moveRight) Player.MoveRight();
if (_moveUp) Player.MoveUp();
if (_moveDown) Player.MoveDown();
}
// You could of course override the OnKeyDown() method instead,
// assuming the handler is in the Form subclass generating the
// the event.
public void MainForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.IsRepeat)
{
// Ignore key repeats...let the timer handle that
return;
}
switch (e.KeyCode)
{
case Keys.Up:
_moveUp = true;
break;
case Keys.Down:
_moveDown = true;
break;
case Keys.Left:
_moveLeft = true;
break;
case Keys.Right:
_moveRight = true;
break;
}
_DoMovement();
_movementTimer.Start();
}
public void MainForm_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Up:
_moveUp = false;
break;
case Keys.Down:
_moveDown = false;
break;
case Keys.Left:
_moveLeft = false;
break;
case Keys.Right:
_moveRight = false;
break;
}
if (!(_moveUp || _moveDown || _moveLeft || _moveRight))
{
_movementTimer.Stop();
}
}
Do note that the timer objects in .NET have limited resolution. I show an interval of 100 ms (10 times per second) above (same as in the other question's answer), and this is about as frequent an update as you're going to reliably get. Even then, the timer's Tick event may not (and probably won't) be raised on exactly 100 ms intervals. There will be some variation back and forth. But it will be close enough for a basic game.
If you need more precision than that, you will have to implement your own state-polling-and-animation loop somewhere. That's a whole other ball o' wax. :)

A subjectivly elegent approach:
public partial class Form1 : Form
{
private static Timer timer;
private static bool[] keys_down;
private static Keys[] key_props;
private void Form1_Load(object sender, EventArgs e)
{
keys_down = new bool[4];
key_props = new []{Keys.A, Keys.D, Keys.W, Keys.S};
timer = new Timer();
timer.Interval = 15; // Roughly 67 FPS
timer.Tick += tick;
timer.Start();
KeyDown += key_down_event;
KeyUp += key_up_event;
... // More things to do when the form loads.
}
private void tick(Object source, EventArgs e)
{
... // Do this every timing interval.
byte n = 0;
foreach (var v in keys_down)
{
if (n == 3 && v)
... // If the "s" key is being held down, no key delay issues. :)
n++;
}
...
}
private void key_down_event(object sender, KeyEventArgs e)
{
byte n = 0;
foreach (var v in keys_down)
{
if (e.KeyCode == key_props[n])
keys_down[n] = true;
n++;
}
}
private void key_up_event(object sender, KeyEventArgs e)
{
byte n = 0;
foreach (var v in keys_down)
{
if (e.KeyCode == key_props[n])
keys_down[n] = false;
n++;
}
}
public Form1()
{
InitializeComponent();
}
}

I was looking for solutions to create a small copy of Flappy Bird. Perhaps my decision will help someone.
I used the addition of a player position with a variable in timer to simulate gravity. When I press W, I turned off the further reception of the command using bool and simply inverted gravity
private void time_Tick(object sender, EventArgs e)
{
if (bird.Location.Y >= 540)
{
bird.Location = new Point(bird.Location.X, 540);
}
else
{
bird.Location = new Point(bird.Location.X, bird.Location.Y+grav);
}
}
private void Form1_KeyPress(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.W && press == false)
{
press = true;
grav = -10;
}
return;
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.W && press == true)
{
press = false;
grav = 5;
}
return;
}

Related

How to make continuous movement using keydown event?

Currently, this code runs fine, and moves the picturebox, but it always moves it once, waits about a second, and then continues to move it. How do I make the movement keep going instead of stopping for a second?
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
x = pictureBox1.Location.X;
y = pictureBox1.Location.Y;
if (pictureBox1.Location.X > 0)
{
pictureBox1.Location = new Point(x - 10, y);
}
}
}
One way to achieve this outcome is to use a Timer and enable it on KeyDown event and disable it on KeyUp event. When MoveTimer.Tick occurs (in this case every 25 ms or so), handle the event by moving "once" to the left until the key is released.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
MoveTimer.Tick += (sender, e) =>
{
pictureBox1.Location = new Point(
pictureBox1.Location.X - 10,
pictureBox1.Location.Y);
};
}
Timer MoveTimer = new Timer { Interval = 25 };
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if(e.KeyData == Keys.A)
{
MoveTimer.Enabled = true;
}
}
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
MoveTimer.Enabled = false; // No need to check which key
}
}

How to restart timer?

I have this Code:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyData == Keys.Left)
{
left = true;
right = false;
down = false;
}
}
private void timerMoving_Tick(object sender, EventArgs e)
{
if(Ghost.Bounds.IntersectsWith(panel3.Bounds))
{
timerMoving.Stop();
}
if(left)
{
Ghost.Left -= 5;
timerMoving.Start();
}
}
In the above code as my Ghost(which is moving down) hits the panel3 boundary it stops.
I want my timer to start again as i press Left,Right or up key and only stop when it's moving down,hitting panel3. I tried doing this:
if(left)
{
Ghost.Left -= 5;
timerMoving.Start();
}
but nothing happens, Why?
The simple (though not the optimal) way to achieve this goal pertinent to your task description is by adding the line shown in the following code snippet:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Left)
{
// add this line
if(!timerMoving.Enabled) timerMoving.Start();
left = true;
right = false;
down = false;
up = false;
}
}
and removing this line as shown below:
if (left)
{
Ghost.Left -= 5;
//timerMoving.Start(); - comment off
}
Hope this may help.

Can't use KeyDown and KeyUp events properly? (Visual C# Windows Form)

I am having problems in breaking a loop (apparently) with the KeyUp event; Character moves, but then I can't make it stop after releasing the key. Looks like I am doing something wrong.
What could I change in this code for it to work? Thanks for the help!
private void Character_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
XSpeed = 1;
}
for (; e.KeyCode == Keys.A;)
{
Thread.Sleep(50);
Character.Left -= XSpeed;
if (XSpeed == 0)
{
break;
}
}
}
private void Character_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
XSpeed = 0;
}
}
The problem here is that you are never going out from the Character_KeyDown handler does not terminate. Because of that, your bit of code in the Character_KeyUp is never executed.
The root issue that you may not realize is that you only have a single UI thread (at least in all UI frameworks that I know such has been the case), and you are monopolizing it with your for loop.
In order to do the right thing, something like WPF's Dispatcher.BeginInvoke, or DispatcherTimer can be used. (If you use WPF). If you can tell us which UI framework you are using, we might be able to come up with a satisfactory code sample.
Here is how you might do it with a DispatcherTimer in WPF:
// Add that field to your class.
private readonly DispatcherTimer moveLeftTimer;
// In the constructor, add the lines inside:
YourClassName() // This line is a stub - I do not know your class name.
{
moveLeftTimer = new DispatcherTimer()
{
Interval = TimeSpan.FromMilliseconds(50)
};
moveLeftTimer.Tick += MoveLeft;
}
private void MoveLeft(object source, EventArgs e)
{
Character.Left -= XSpeed;
}
private void Character_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
moveLeftTimer.IsEnabled = true;
}
}
private void Character_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
moveLeftTimer.IsEnabled = false;
}
}
In order to adapt for Windows Forms, use the Timer class instead of DispatcherTimer, and the property is named Enabled instead of IsEnabled.
That's because you are doing everything on one thread, in your case it happens to be the Main UI thread. All actions are done sequentially. It does't matter that you have a handler to change XSpeed = 0, it's not going to process until the Character_KeyDown is done. Put break points in both and you will see the point.
What you need to do is to put your processing on the background thread and release your UI handlers.
Task.Factory.StartNew creates a background thread and executes an action you give it.
now if you need to update something that belongs to the UI thread, you gotta do it on the UI thread...
private void Character_KeyDown(object sender, KeyEventArgs e)
{
Task.Factory.StartNew(() =>
{
if (e.KeyCode == Keys.A)
{
OnUI(() => XSpeed = 1);
}
for (; e.KeyCode == Keys.A;)
{
Thread.Sleep(50);
OnUI(() => Character.Left -= XSpeed);
if (XSpeed == 0)
{
break;
}
}});
}
private void Character_KeyUp(object sender, KeyEventArgs e)
{
Task.Factory.StartNew(() =>
{
if (e.KeyCode == Keys.Left)
{
OnUI(() => XSpeed = 0);
}
}
}
here's a sample for OnUI:
private void OnUi (Action action)
{
if (_dispatchService == null)
_dispatchService = ServiceLocator.Current.GetInstance<IDispatchService>();
//or _dispatchService = Application.Current.Dispatcher - whatever is suitable
if (_dispatchService.CheckAccess())
action.Invoke ();
else
_dispatchService.Invoke(action);
}

How to fix this Two keys pressed conflict?

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
Typically you don't hande the key events directly for these kinds of things. Instead, you keep track of what keys are currently pressed. Physics calculations are done on some interval, which can be done with a timer. Quick and dirty example below. However, this is not the kind of thing you should be attempting with WinForms.
private const int ACCELERATION = 1;
private HashSet<Keys> pressed;
private int velocityX = 0;
private int velocityY = 0;
public Form1()
{
InitializeComponent();
pressed = new HashSet<Keys>();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
pressed.Add(e.KeyCode);
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
pressed.Remove(e.KeyCode);
}
private void timer1_Tick(object sender, EventArgs e)
{
car.Location = new Point(
car.Left + velocityX,
car.Top + velocityY);
if (pressed.Contains(Keys.W)) velocityY -= ACCELERATION;
if (pressed.Contains(Keys.A)) velocityX -= ACCELERATION;
if (pressed.Contains(Keys.S)) velocityY += ACCELERATION;
if (pressed.Contains(Keys.D)) velocityX += ACCELERATION;
}

C# Keydown/Keyevents if no key is pressed

I am programming something right now in c#, trying to "convert" a console application to a windows Forms application and I wanted to do something like the following:
if("keypress == nokey")
{
system.threading.thread.sleep ***
}
while(nokeyispressed)
{
system.threading...
}
Basically ask if no key is pressed sleep for some time and this.close();
so that if no key is pressed, do something...
I just can't get it to work.
I would be very greatful for some help..:D
If no key pressed, then no KeyDown event raised. So, your handler will not be called.
UPDATE (option with loop removed, because timer will make same for you as loop on different thread with sleep timeouts):
Here is sample with timer:
private bool _keyPressed;
private void TimerElapsed(object sender, EventArgs e)
{
if (!_keyPressed)
{
// do what you need
}
}
private void KeyDownHandler(object sender, KeyEventArgs e)
{
_keyPressed = true;
switch (e.KeyCode)
{
// process pressed key
}
_keyPressed = false;
}
UPDATE: I think good idea to verify how many time elapsed since last key down before decide if no keys were pressed
private DateTime _lastKeyDownTime;
private const int interval = 100;
private void LoadHandler(object sender, EventArgs e)
{
// start Threading.Timer or some other timer
System.Threading.Timer timer = new System.Threading.Timer(DoSomethingDefault, null, 0, interval);
}
private void DoSomethingDefault(object state)
{
if ((DateTime.Now - _lastKeyDownTime).TotalMilliseconds < interval)
return;
// modify UI via Invoke
}
private void KeyDown(object sender, KeyEventArgs e)
{
_lastKeyDownTime = DateTime.Now;
switch (e.KeyCode)
{
// directly modify UI
}
}

Categories

Resources