Strange occurrence with input
The following is being called from Update. What I expected to happen is that when a key press occurs, QueuedMove is set to the appropriate direction.
Once the move timer hits 0, the move occurs.
Then the QueuedMove is reset to Still so another move doesn't occur.
If they continue to hold the key, I expect it to set the QueuedMove again each update. But if the key is not being held, only 1 move should occur.
What is actually happening, is when I press the key, no matter how briefly, the move occurs twice.
I added a couple of debug statements, on moving left, to see what was going on, and the log shows the Queued Left, then Moving, then Queued Left again, then moving again.
Can anyone see what I might be doing wrong here, that would cause this to move twice?
I have been staring at this for hours, and can't seem to figure out where I am going wrong.
public void ProcessKeyboardInput()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
Debug.Log("Queued Left");
QueuedMove = MovingDirection.Left;
}
if (Input.GetKey(KeyCode.RightArrow))
QueuedMove = MovingDirection.Right;
if (Input.GetKey(KeyCode.DownArrow))
QueuedMove = MovingDirection.Down;
if (Input.GetKey(KeyCode.UpArrow))
QueuedMove = MovingDirection.Up;
MoveTime -= Time.deltaTime;
if (MoveTime < 0)
{
if (QueuedMove != MovingDirection.Still)
{
Debug.Log("Moving");
MovePlayer(QueuedMove);
QueuedMove = MovingDirection.Still;
MoveTime = MoveDelay;
}
}
}
Any help is greatly appreciated! -Larry
Answer by Dragate · Dec 05, 2017 at 07:38 AM
Something is fishy with that MoveTime -= Time.deltaTime; I believe it's a problem that it's being decremented even when MovingDirection.Still. Could you try
if (QueuedMove != MovingDirection.Still){
if(MoveTime < 0){
Debug.Log("Moving");
MovePlayer(QueuedMove);
QueuedMove = MovingDirection.Still;
MoveTime = MoveDelay;
}else{
MoveTime -= Time.deltaTime;
}
}
EDIT: Explanation is that when at MovingDirection.Still, the timer was counting. When you pressed an arrow (which probably is pressed for more than one frame, even for fast presses), you instantly moved at that frame (since timer had counted at .Still and was already negative) and on next frame it buffered another movement. So, that's 2 movements with 1 press.
You got it!!! Not sure why I wasn't spotting this as being a problem. Didn't expect that being decremented every frame to cause this to occur, but it did.
I appreciate your help on this! -Larry
Your answer
![](https://koobas.hobune.stream/wayback/20220612144013im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Why pressing the up and down key doesn't mean the body in correct forward and back direction? 1 Answer
Unity input not working "up arrow",KeyBoard Up arrow input not working 0 Answers
Why doesn't Input.GetButtonDown() work with my ps4 controller? 0 Answers
input.getkey keycode scrollwheel - Is this even possible? 0 Answers
How can I get inputs in several steps? 0 Answers