Delay keyboard input help
Posted
by Stradigos
on Stack Overflow
See other posts from Stack Overflow
or by Stradigos
Published on 2010-04-14T18:34:57Z
Indexed on
2010/04/14
21:53 UTC
Read the original article
Hit count: 396
I'm so close! I'm using the XNA Game State Management example found here and trying to modify how it handles input so I can delay the key/create an input buffer.
In GameplayScreen.cs I've declared a double called elapsedTime and set it equal to 0.
In the HandleInput method I've changed the Key.Right button press to:
if (keyboardState.IsKeyDown(Keys.Left))
movement.X -= 50;
if (keyboardState.IsKeyDown(Keys.Right))
{
elapsedTime -= gameTime.ElapsedGameTime.TotalMilliseconds;
if (elapsedTime <= 0)
{
movement.X += 50;
elapsedTime = 10;
}
}
else
{
elapsedTime = 0;
}
The pseudo code:
If the right arrow key is not pressed set elapsedTime to 0. If it is pressed, the elapsedTime equals itself minus the milliseconds since the last frame. If the difference then equals 0 or less, move the object 50, and then set the elapsedTime to 10 (the delay).
If the key is being held down elapsedTime should never be set to 0 via the else. Instead, after elapsedTime is set to 10 after a successful check, the elapsedTime should get lower and lower because it's being subtracted by the TotalMilliseconds. When that reaches 0, it successfully passes the check again and moves the object once more.
The problem is, it moves the object once per press but doesn't work if you hold it down. Can anyone offer any sort of tip/example/bit of knowledge towards this? Thanks in advance, it's been driving me nuts. In theory I thought this would for sure work.
CLARIFICATION
Think of a grid when your thinking about how I want the block to move. Instead of just fluidly moving across the screen, it's moving by it's width (sorta jumping) to the next position. If I hold down the key, it races across the screen. I want to slow this whole process down so that holding the key creates an X millisecond delay between it 'jumping'/moving by it's width.
EDIT: Turns out gameTime.ElapsedGameTime.TotalMilliseconds is returning 0... all of the time. I have no idea why.
© Stack Overflow or respective owner