Hi,
I was working on a script to change the direction of velocity of my player on pressing a key. Initially, I was using the GetButtonDown() function inside FixedUpdate() along with the other physics related work. As asked by many in the Answers section, the button down was not registering every time. And thanks to those same answers I managed to figure out that I should use my inputs in Update().
Now, if after button down, Update() is called before FixedUpdate(), I loose my button press. So, I resorted to write the following code:
Update()
{
if (!buttonPress)
{
buttonPress = Input.GetButtonDown("Turn");
}
}
FixedUpdate()
{
if (buttonPress)
{
//Do required work
buttonPress = false;
}
}
I kind of have an OCD to make my code beautiful, although I know it is not always possible. Still, is there any other way to achieve the same functionality in a more elegant way?
This is because due to varying frame rates, it is possible that Update() is called twice in succession without FixedUpdate() being called even once. Lets say, in frame 1, Update() recognizes my input and sets the value to true. If Update() is called again, the value will be set to false(since there is no more button down). Thus, if FixedUpdate() is called next, it won’t recognize the input.
What I did was a bit procedural. lordofduct’s thread actually gives the kind of solution that I require. But, I need to understand it first:smile:. And I am sleepy…
It’s basically just creating a class to store the historic state of the key press (the example dealt with keyboard input, you’ll want to reimplement it using GetButton rather than GetKey).
Every frame you update the history by calling ‘Update’ on the object, this determines if the key was just pressed, held, or released.
You can then poll the corresponding method to determine the state, named in a manner similar to unity’s inputs.
Thanks for the explanation. I was actually thinking of going through your code tomorrow, but your explanation woke me up:smile:. I guess I will try to implement it before retiring for the day.