Home > Back-end >  Unity Input.GetKeyDown() event frequently missed
Unity Input.GetKeyDown() event frequently missed

Time:12-18

I'm working on a test project to experiment with Rigidbody in Unity. I worked on horizontal movement and jump actions, but I have a problem. Input.GetKeyDown() seems to not catch my key down event most of the time. I tried looking at possible solutions that suggested catching key inputs in Update() and corresponding with Rigidbody interactions with FixedUpdate(). When I tried this, I saw little to no improvement. Here is the script I'm working on right now:

public class PlayerScript : MonoBehaviour
{
    [SerializeField] private float jumpConstant = 5.0f;
    [SerializeField] private int walkSpeed = 10;
    private bool jumpDown;
    private float horizontalInput;
    private Rigidbody rbComponent;

    // Start is called before the first frame update
    void Start()
    {
        rbComponent = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void Update()
    {
        CheckIfJumpKeyPressed();
        GetHorizontalInput();
    }

    void FixedUpdate()
    {
        JumpIfKeyPressed();
        MoveHorizontal();
    }

    void CheckIfJumpKeyPressed()
    {
        jumpDown = Input.GetKeyDown(KeyCode.Space);
    }

    void JumpIfKeyPressed()
    {
        if (jumpDown)
        {
            jumpDown = false;
            rbComponent.AddForce(Vector3.up * jumpConstant, ForceMode.VelocityChange);
            Debug.Log("Jumped!");
        }
    }

    void GetHorizontalInput()
    {
        horizontalInput = Input.GetAxis("Horizontal");
    }

    void MoveHorizontal()
    {
        rbComponent.velocity = new Vector3(horizontalInput * walkSpeed, rbComponent.velocity.y, 0);
    }
}

Thank you in advance.

CodePudding user response:

You are overwriting your input if an extra frame occurs between your input and the physics frame. You should make sure a lack of input does not overwrite a detected input:

void CheckIfJumpKeyPressed()
{
    jumpDown |= Input.GetKeyDown(KeyCode.Space);
}

or, equivalently:

void CheckIfJumpKeyPressed()
{
    if (!jumpDown)
    {
        jumpDown = Input.GetKeyDown(KeyCode.Space);
    }
}

Or even:

void CheckIfJumpKeyPressed()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        jumpDown = true;
    }
}

Whichever you find most readable.

  • Related