Search code examples
c#animationunity-game-enginecurves

How to make the Jump animations using curves smoothly?


I've been working on an endless runner game using unity 5 engine studying some examples. I applied jump action to my character. It did work fine but I wanted it to be bit perfect so I implanted the jump using curves with this example, came across this issue. That is after applying curves for the character controller with some adjustments, now when I jump, the curves starting to adjust the controller after I touched a platform (the ground) which make the jump unrealistic. I did tried to achieve the jump using fixed Update method, since the game is an endless runner which basically updates everything frame by frame it did not work. How do I achieve a realistic jump? below is what I tried so far.

if (controller.isGrounded)
    {
        verticalVelocity = -0.5f; //upward thrust / jump height
            if (currentBaseState.fullPathHash == locoState) // is character in moving state
            {
                if (Input.GetButtonDown("Jump"))
                {
                    verticalVelocity = 18f;
                    anim.SetBool("Jump", true);
                }
            }
            else if (currentBaseState.fullPathHash == jumpState) //Is character in jump state
            {
                if (!anim.IsInTransition(0))
                {
                    if (useCurves)
                    {
                        controller.height = anim.GetFloat("ColliderHeight"); //get the controller height using curves
                        controller.center = new Vector3(0f, anim.GetFloat("ColliderY"), 0f); //Get the controller Y axis using the curves (center of chr ctrlr)
                    }

                    anim.SetBool("Jump", false);

                }
    // Applying curves
                Ray ray = new Ray(transform.position + Vector3.up, -Vector3.up);
                RaycastHit hitInfo = new RaycastHit();

                if (Physics.Raycast(ray, out hitInfo))
                {
                    print(ray.ToString());
                    if (hitInfo.distance > 1.75f)
                    {
                        anim.MatchTarget(hitInfo.point, Quaternion.identity, AvatarTarget.Root, new MatchTargetWeightMask(new Vector3(0, 1f, 0), 0), 0.03f, 0.6f);
                    }
                }    

            }
    }

Character jumping at start Character jumping at start

Char controller touching the ground Char controller touching the ground

Result after touching the ground Result after touching the ground

Help would be deeply appreciated


Solution

  • Your bit of code that adjusts the controller based on the curves is inside the if statement asking if the character is grounded.

    if (controller.isGrounded)
    {
     ...
    }
    

    that way it will adjust only when the character is touching the ground.