Home>

I was able to do a jump operation in the unity 2D action game development,
I kept jumping on the directional keys and jumped many times.
How can I make one jump when I press the arrow key once?

*Because I am a beginner to programming, I do not know how to change the operation key input. .. ..

If i keep pressing the arrow keys, you will repeatedly jump.

Applicable source code
      // act when keyed
        float horizontalKey = Input.GetAxis("Horizontal");
        float verticalKey = Input.GetAxis("Vertical");
        float xSpeed ​​= 0.0f;
        float ySpeed ​​= -gravity;
        if (isGround)
        {
            if (verticalKey >0)
            {
                ySpeed ​​= jumpSpeed;
                jumpPos = transform.position.y;// record the jumped position
                isJump = true;
                jumpTime = 0.0f;
            }
            else
            {
                isJump = false;
            }
        }
        else if (isJump)
        {
            // Is the up arrow key pressed?
            bool pushUpKey = verticalKey>0;
            // Is the current height below the flight height
            bool canHeight = jumpPos + jumpHeight>transform.position.y;
            // Is the jump time too long?
            bool canTime = jumpLimitTime>jumpTime;
            if (pushUpKey&&canHeight&&canTime&&!isHead)
            {
                ySpeed ​​= jumpSpeed;
                jumpTime += Time.deltaTime;
            }
            else
            {
                isJump = false;
                jumpTime = 0.0f;
            }
        }
What I tried

Key input method
if(Input.GetKeyDown("Jump"))
I also tried replacing it with
I got an error and it didn't work.

Supplementary information (FW/tool ​​version, etc.)

Please provide more detailed information here.

  • Answer # 1

    As a general method, the character's ground contact is determined. That is, determine if the character is standing on the ground. And make sure you only jump when you are standing on the ground.

    Unity 2D If you googling with the ground contact judgment, there will be a lot of hits, but here is an example.

    How to make Unity 2D action [ground contact judgment]