Reading Input in Update() and using it in FixedUpdate()

Hey all,
I’ve read a bunch about FixedUpdate and Update and my intuition tells me that anything that is a quick button press should not be put in FixedUpdate because that could generate input loss. Therefore, if I wanted to implement a jump mechanic, I would GetKeyDown in Update, and store that information somewhere, then use it in FixedUpdate. It works fine so far.

Here is how I did it. I keep a HashMap of Strings → bools which basically represent keys to bools. Example: Jump → false means the Jump key has not been pressed. If I press the jump key, the HashMap updates Jump to true, then fixed update uses that information to tell if the player can jump or not. I use HashMaps for fast lookups.

However, I do not want to store that information for a long time. I could have other abilities that are situational, say Dropping down a platform. If I double tap down key, the HashMap will have: DropDown → true. However, there is no platform to drop down off of, so the information stays true for a long time until I actually am on a platform. So I was thinking of keeping the inputs true for a while then reverting them to false. My question is:

How long should I keep them true before resetting them? 5 frames? 1 frame? 10 frames? a second?
In addition, should the timer be physics related? (i.e use internal clock VS using normal counters)

The way I do this sort of thing would be to replace the bool with a float. e.g.:

float buttonDownTrueUntil = -1f;

void Update() {
if (Input.GetKeyDown(whatever) ) {
buttonDownTrueUntil = Time.time + 0.5f;
}
}

void FixedUpdate() {
if (Time.time < buttonDownTrueUntil) {
buttonDownTrueUntil = -1f;
// and whatever else
}
}

With this method, it’ll be active for a maximum of a certain amount of time, OR until the press is used.

2 Likes

That’s a really neat way of doing it! Thank you :slight_smile:
Also just another question, for cooldowns in general, should I increment by Time.deltaTime or Time.fixedDeltaTime?
For example, if I have a dash that should be on cooldown for 1 second (virtual time, not real time), then how should I handle the timer?

I’d actually handle it pretty much the same way as above - don’t increment anything, but instead just set a target time and watch for that time.

Though, if you’re picking one or the other to increment with, always use .deltaTime, which will actually set itself to .fixedDeltaTime if you’re in FixedUpdate - in other words, the only time it’d be appropriate to use .fixedDeltaTime, the value of .deltaTime will be the same.

Thank you so much!