Reputation: 195
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.
Upvotes: 1
Views: 546
Reputation: 5762
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);
}
Upvotes: 1
Reputation: 13148
here's a simple pseudo-code example:
// to cancel immediately
if key is pressed this frame, but was released last frame
begin effect
else if key is pressed this frame, and also was last frame
increase magnitude of effect
else if key is released this frame and effect is active
end effect
// or to gradually decrease
if key is pressed this frame, and effect is inactive
begin effect
else if key is pressed this frame, and effect is active
increase magnitude of effect
else if key is released this frame and effect is active
decrease magnitude of effect
if magnitude decreased enough, end effect
To specifically measure the duration as you say would be something like this:
public void Update(GameTime pGameTime)
{
private TimeSpan mKeyDuration = TimeSpan.FromSeconds(0);
...
if key is pressed this frame
mKeyDuration += pGameTime.ElapsedGameTime;
else if key was pressed last frame
mKeyDuration = TimeSpan.FromSeconds(0);
...
}
Upvotes: 0
Reputation: 14153
To Detect a single keypress...
lastKeyboardState = CurrentKeyState;
CurrentKeyState = Keyboard.GetState();
if ((CurrentKeyState.IsKeyUp(Keys.Enter)) && (lastKeyboardState.IsKeyDown(Keys.Enter))
{
//Enter was pressed
}
To detect a key being held down...
lastKeyboardState = CurrentKeyState;
CurrentKeyState = Keyboard.GetState();
if (CurrentKeyState.IsKeyDown(Keys.Enter)
{
//Enter was pressed (You could do BeamSize++ here
}
That seems the best way to do it. Is that the method you are already using?
Upvotes: 0