hi there
apologies for the noobiness of this question!
i am authoring my first unity game and have come across a simple but painful issue.
I have googled but was surprised that i could not find the answer to what must be a common issue???!!?
I have the following in the FixedUpdate method on a game object with a rigid body component:
if(Input.GetKeyDown(KeyCode.S)){
Debug.Log ("s pressed");
if( playstate == 0){
spinUp();
}
}
My issue is that I am getting several triggers happening in quick succession when I consult the logs. These are firing several different callbacks.
is there a common practice method for debouncing key presses in unity or have i missed something much more fundamental?
many thanks in advance!!!
4 Answers
4
Input checks in Fixed Update don’t work properly.
Lets say I just pressed a key, Input will return true for that key until the end of one frame. But since FixedUpdate is independant from this loop, it will only return true in there, if FixedUpdate gets called inbetween the start and end of a frame rendered. Most of the time you will have a higher framerate than the 50fps of FixedUpdate. Lets say you presed the key, three Update’s are called and then FixedUpdate After the first Update the Input.KeyDown is already false.
So in short do Input calls in Update and not FixedUpdate 
Hope this helps, Benproductions1
You should not put it in fixedupdate(), but in update().
Input.GetKeyDown() is set every Update() cycle. You are using it inside the FixedUpdate() which sounds like it is getting called multiple times per Update() cycle.
I would check Input on each Update() then call spinUp() there, or set a flag to spinUp() on the following FixedUpdate().
thanks for your replies!
I was using FixedUpdate because I am adding angular velocity to a rigid body. I read that I need to keep any rigid body scripts within FixedUpdate to keep the physics engine stable.
Do I disregard this advice or is there a common way to add debounced key presses to rigid bodies within the FixedUpdate method?
many thanks
@glassman3d : you have been told several times on this question to not post comments as answers and please accept an answer. Do it, don't just walk away. Watch : http://video.unity3d.com/video/7720450/tutorials-using-unity-answers Actually I have no patience at the moment. I am accepting an answer on your behalf. Edit : sorry Unitraxx, I went with the answer with most votes, but you all got a vote from me =]
– AlucardJay@alucardj Thank you! Is it possible (and ok) to suspend users who obviously have an answer to their question, but don't accept it?
– Benproductions1He actually did post a decent question, so he should not be punished. I just think he doesn't get any notification that we are still talking to him.
– Unitraxxhello apologies all i was away from my machine, i really appreciate your answers and have deleted my incorrect posts. this was my second post in your forum so i am still learning the etiquette
– glassman3d