Difference between revisions of "Using Timers"
(Created page with "Key presses on a game can cause difficult movement because a single press could be read multiple times. To get around this we can use a timer, the first press will start the t...") |
|||
Line 5: | Line 5: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | So in the | + | So in the Game1.cs you need to define a timer, this should be with the other variable declarations: |
<syntaxhighlight lang=csharp> | <syntaxhighlight lang=csharp> | ||
Line 11: | Line 11: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | Find the bit you want to time (for example one of the key presses): | |
<syntaxhighlight lang=csharp> | <syntaxhighlight lang=csharp> |
Latest revision as of 13:22, 22 January 2019
Key presses on a game can cause difficult movement because a single press could be read multiple times. To get around this we can use a timer, the first press will start the timer and subsequent presses will be disabled for a period of time. To user a timer you need to add the following to the using section of Game1.cs:
using System.Timers;
So in the Game1.cs you need to define a timer, this should be with the other variable declarations:
Timer aTimer = new System.Timers.Timer();
Find the bit you want to time (for example one of the key presses):
if (currentKeyboardState.IsKeyDown(Keys.Down))
{
if (!aTimer.Enabled)
{
// what ever you need the keypress to do
aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval=100;
aTimer.Enabled=true;
}
The timer is set for 100 milliseconds, and when the timer elapses it will run a timed event called OnTimedEvent.
Finally we need to create the method below for OnTimedEvent:
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
aTimer.Enabled = false;
}