Way to implement handling duration of a keypress

I'm using XNA (C#) to develop a 2D platformer. I was wondering for the best way to handle holding down a specific button. For example the more you hold down the larger the laser beam gets.

So far, since I'm already using the input mechanism that holds the 2 last states of the Keyboard, I can make an extra check each update cycle to increase the duration. But, this approach is rather limited since it only handles a specific button (fire button i.e.) and it should do the trick, but i was wondering if maybe there's a more general solution to the problem.

Answers


float ElapsedSecondsPerFrame = (float) gametime.Elapsed.TotalSeconds;

KeyFirePressedTime = Keyboard.GetState().IsKeyDown(FireKey) 
                         ? (KeyFirePressedTime + ElapsedSecondsPerFrame ) 
                         : 0;

Generic method

Dictionary<int, float> PressedKeysTime = new ...


void Update(float Elapsed)
{
      List<int> OldPressedKeys = PressedKeysTime.Keys.ToList();
      foreach (int key in Keyboard.GetState().GetPressedKeys.Cast<int>())
      {
           if (!PressedKeysTime.ContainsKey(key)) 
           {
                PressedKeysTime[key] = 0;
           } else {
               OldPressedKeys.Remove(key);
               PressedKeysTime[key] += Elapsed;
           }
      }
      foreach (int keynotpressed in OldPressedKeys) 
          PressedKeysTime.Remove(keynotpressed);

}

Need Your Help

Stop adding product to cart process in Magento

magento

The prices of our website depend on a webservice that get the prices from an external database. Sometimes this process fails and set the product price to '0'.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.