Simple way to have smooth jumping without rigid body! finally!

With much tinkering, I accidentally put together a very basic way to have your character controller (or other homebrew script) ascend gracefully instead of teleport and then descend. I know most of us figure out the slow falling gravity part, but the jumping is always a pain in the butt. So here’s the solution I’d like to share with you all because a few hours of googling were useless to me and probably others.

//keep camera on top of body
        Vector3 camPos = body.position + (body.up*1);
        transform.position = camPos;

        Vector3 movement = (transform.forward * moveZ * Time.deltaTime) + (transform.right * moveX * Time.deltaTime);
        lastFlag = controller.collisionFlags;

        if(lastFlag == CollisionFlags.CollidedBelow)
        {
            movement.y = 0;
        }
        else if(lastFlag == CollisionFlags.None)
        {
            movement.y -= (gravity * Time.deltaTime) - (vertical_force * Time.deltaTime);
            movement.y = Mathf.Clamp(movement.y, maxFall*-1, maxFall*10);
            if(vertical_force > 0)
            {
                vertical_force -= gravity * Time.deltaTime;
            }
            if(vertical_force < 0)
            {
                vertical_force = 0;
            }
        }

        if(jump)
        {
            vertical_force = 20;
        }

        //transform.position += movement;
        controller.Move(movement);

No coroutines :smile: just a slight modification to the gravity line we all come up with. My gravity force is 10, so I chose a vertical/jump force of 20. If you choose 10 or less, you will not jump, because gravity will immediately overcome your vertical force. Jump is set in another function that polls the keyboard for input.

jump = (lastFlag == CollisionFlags.CollidedBelow) && Input.GetKey(KeyCode.Space);

I don’t know what the norm is for using Time.deltaTime in multiple places instead of making a temporary variable at the beginning of each update, but you get the idea here.

3 Likes

Know this is kinda late, but where is the code located? is it in void update, or is it just code to plug in?

5 years is “kinda late”? Also this guy hasn’t been seen on the forum since 2016.

You could put it in update, but The poster assumes that you have some variables (such as “controller”) already declared and assigned a value. Don’t expect to copy and paste it and it necessarily work as-is.

2 Likes

For a short moment I was hopefully he had reappeared… then disappointment when I realized it was a necro.