Better option than GetKeyUp and GetKeyDown?

Greetings.

I am attempting to build a simple 3d platformer to practice what I’ve learned. Right now I have a small cube as the player character who can move around and jump. Next, I am trying to implement a mechanic where the player can hold down the Z button to stop their velocity; then when they let go, they’ll resume the velocity they were going. I am also implementing a mechanic where they can hold the X button and, upon release, they’ll head in the opposite direction. With the code I have now, it works but only occasionally. Here is my code for these two mechanics; I’ve placed them in FixedUpdate.

     if (Input.GetKeyDown(KeyCode.Z))
    {
        velStorage = rb.velocity;
        allowMovement = false;
        rb.useGravity = false;
        signal = true;
        rb.velocity = Vector3.zero;
    }
    /*
    if (Input.GetKey(KeyCode.Z))
    {
        rb.velocity = new Vector3(0f,0f,0f);
        rb.useGravity = false;
    }
    */
    if (Input.GetKeyUp(KeyCode.Z))
    {
        rb.velocity = velStorage;
        allowMovement = true;
        rb.useGravity = true;
        signal = false;
        velStorage = Vector3.zero;
    }

    if (Input.GetKeyDown(KeyCode.X))
    {
        allowMovement = false;
        antiVelStorage = -rb.velocity;
        rb.velocity = Vector3.zero;
        rb.useGravity = false;
        antiSignal = true;
    }
    /*
    if (Input.GetKey(KeyCode.X))
    {
        rb.velocity = new Vector3(0f, 0f, 0f);
        rb.useGravity = false;
    }
    */
    if (Input.GetKeyUp(KeyCode.X))
    {
        allowMovement = true;
        rb.velocity = antiVelStorage;
        antiVelStorage = Vector3.zero;
        rb.useGravity = true;
        antiSignal = false;
    }

The problem I am experiencing is ocasionally the returned velocity will be Vector3.zero. Also sometimes when I release the button it won’t call the second if statement (for either of the mechanics) and the cube will just float there in zero gravity until I press either of the buttons again. So to me, it seems that either my computer or Unity is having trouble regeristering the Inputs from the Z & X Button. I’m wondering if there is a different way to code this or if there is a preference I can switch in Unity that’ll make the Input more consistent.

Thanks Much!

The problem is your input in FixedUpdate.

The Input is linked to the OS and it runs once per frame. But your FixedUpdate does not necessarily run each frame. So you’ll have misses.

Consider you have FixedUpdate at 60fps and computer runs 120fps. It means you have one FixedUpdate for 2 updates. That is a 50% chance of miss with GetKeyUp/Down since does only return true for one frame.

Solution, move the code to Update and forward the data to FixedUpdate. Actuallly your code is such that you can just move it to Update as you do not have any method for forces.

Using GetKey or GetAxis is less of a problem in FixedUpdate since they return true over a period.