简体   繁体   中英

I'm having problems to implement jump properly in Unity 2D

I have written this code for my controller in Unity. The problem is that the jump in Y axis has different height than the jump for X and Y axis simultaneously.

// Update is called once per frame
void FixedUpdate()
{

    Debug.Log(rigidbody.velocity);

    float inputX = Input.GetAxis("Horizontal");

    //Movement X
    if(inputX != 0 && isGrounded)
    {
        animator.SetBool("isWalking", true);
        rigidbody.velocity = new Vector2(inputX*speed, 0);

        //Turn left & right
        if(inputX > 0)
        {
            spriteRenderer.flipX = false;
        } else if (inputX < 0)
        {
            spriteRenderer.flipX = true;
        }
    } else 
    {
        animator.SetBool("isWalking", false);
    }

    //Jump
    if(Input.GetAxis("Jump") > 0 && isGrounded)
    {
        rigidbody.AddForce(Vector2.up * jumpImpulse, ForceMode2D.Impulse);
    }
}

if i understand your code right, you only gives force to X when you are in ground, so i suggest to remove isgrounded variable and use it just for jump for example in your update method

if(isGround){
  if(keypress == y){
    addforce in Y
  }
}

actually im a bit oxided in unity but i hope to be usefull about logical

I am pretty bad myself when it comes to the jumping physics, but i found these links maybe these will help you.

Unity 2d jumping script

https://answers.unity.com/questions/710765/2d-c-jump-script-addforce-1.html

I also want to know which jump is higher. You stated that there is a height difference when you jump without moving vs when you are moving. Which of the two jumps higher? Are you actually sure that one jumps higher than the other or does it just look like one jumps higher? You can test this by placing a platform an test if you can make it.

Sorry I can't me of more help and can only speculate of what might cause the problem. I would recommend however that when you do movement that you multiply it by Time.DeltaTime. This makes the movement time based instead of frame based. This will make the movement feel smoother.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM