Using Timers

From TRCCompSci - AQA Computer Science
Revision as of 13:22, 22 January 2019 by Admin (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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;
 }