Managing key down input and velocity set

Hello,

I’m thinking of something just now that could potentially be an issue in the future.

I have this :

private void FixedUpdate() {
  timer += Time.fixedDeltaTime;
  if (keydown) {
    // Do some physics calculation here
  }

  // do more stuff in there among which some may have a keydown too
}

I know anything physics related should be done in FixedUpdate, and (at least) anything input related (especially single frame stuff like keyDown) should be done in Update.
But here I’m incrementing a timer and do stuff like setting the velocity.

How can I seperate the input part in Update and do the physics in FixedUpdate ?

Thanks !

bool jump;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
            jump=true;
    }

    void FixedUpdate()
    {
        if (jump)
        {
            rb.AddForce(Vector3.up*20);
            jump=false;
        }
    }

I thought of that but it feels sooooo annoying to do it like that for everytime I press a button, for every action.

Is that the only way ?

Thanks for answering btw !

If you want to engineer another way, this is the timing information you will need to consider:

Two good discussions on Update() vs FixedUpdate() timing:

https://jacksondunstan.com/articles/4824

https://johnaustin.io/articles/2019/fix-your-unity-timestep

Here is some timing diagram help:

Yeah I know, I feel the same way! :slight_smile:

Another alternative:

   void FixedUpdate()
   {
      if (Input.GetKey(KeyCode.Space))
      {
         if (canJump)
         {
            rb.AddForce(Vector3.up*20);
            canJump=false;
         }
      }
      else
         canJump=true;
   }

Ok how about this :

I create a static class containing stuff like “ADown, BDown” etc which are booleans, and I create a script that sets those values in Update whenever an input is triggered. I put this script on a gameobject in the scene.

I set its execution priority to very high, then create another script that resets those values in FixedUpdate, also put it on that gameobject and then put its priority to very low.

That should work right ?

All inputs would be set at the beginning of each Update, and reset at the end of each FixedUpdate right ?

Then I would access these booleans in my actions instead of the input value directly

I’ve never had a project that relied so heavily on the KeyDown event that I needed to do anything fancy. But if you’re checking for lots of down events in several FixedUpdates throughout multiple scripts then I can see your idea being worthwhile.

1 Like