Issue with Gravity

So I’m trying to fix my player control script & it’s almost working fine, except for some reason it allows the player to jump fine with the correct gravity, but for some reason, the following line{s} are causing the player to fall more slowly than normal & if continually colliding with something, it just sticks there until the key is let go of then continues to fall more slowly.

Why are these lines

if ( isGrounded == true ) {
    // Current movement
    rb.velocity = new Vector3 (
        moveHorizontal,
        0.0f,
        moveVertical
    ).normalized * speed;
}
else {
    rb.AddForce (
        movementRotation * speed * jumpModifier
    );
}

causing my player to fall at a slower rate & stick to the colliding object until the movement key{s} are let go, than if I press the jump button & let the player fall?

Here’s the function :

void ControlPlayer ( ) {
    moveHorizontal = Input.GetAxis ( "Horizontal" );
    moveVertical = Input.GetAxis ( "Vertical" );
    Debug.Log ( direction );
    Vector3 camForward = cam.transform.forward;
    camForward.y = 0.0f;
    Quaternion camRotationFlattened = Quaternion.LookRotation ( camForward );
    movementRotation = camRotationFlattened * movementRotation;
    if ( isGrounded == true ) {
        // Current movement
        rb.velocity = new Vector3 (
            moveHorizontal,
            0.0f,
            moveVertical
        ).normalized * speed;
    }
    else {
        rb.AddForce (
            movementRotation * speed * jumpModifier
        );
    }
    if ( Input.GetKey ( KeyCode.Space ) || Input.GetKey ( KeyCode.Joystick1Button1 ) && isGrounded ) {
        jumpHeight = ( jumpForce * jumpModifier );
        rb.velocity = new Vector3 (
            rb.velocity.x,
            jumpHeight,
            rb.velocity.z
        );
        isGrounded = false;
    }
    if ( movementRotation.sqrMagnitude > 0.1f && isGrounded ) {
        transform.rotation = Quaternion.Slerp (
            transform.rotation,
            Quaternion.LookRotation ( movementRotation ),
            10.0f
        );
    }
}

Here’s the whole script :

using UnityEngine;

public class ThirdPersonMovement : MonoBehaviour {

    [ Header ( "Target{s}" ) ]
    public Camera cam;
    public Rigidbody rb;

    [ Header ( "Physics" ) ]
    public float speed;
    public float jumpForce = 17.0f;
    public float gravity = 45.0f;
    public float jumpModifier = 2.0f;
    private float jumpHeight = 0.0f;
    private float directionSpeed = 3.0f;
    private float speedPlus = 0.0f;
    private float direction = 0.0f;

    [ Header ( "Grounded Check { Unhidden }" ) ]
    public bool isGrounded = true;

    [ Header ( "Jump Vector3 { Unhidden }" ) ]
    public Vector3 jump;

    private float moveHorizontal;
    private float moveVertical;

    private Vector3 movement;
    private Vector3 movementRotation;
    private Vector3 moveDirection;
    private Vector3 curLoc;
    private Vector3 prevLoc;

    void Awake ( ) {

        cam = Camera.main; // GetComponent <Camera> ( )
        rb = GetComponent <Rigidbody> ( );
        jump = new Vector3 ( 0.0f, 0.0f, 0.0f );

        Physics.gravity = new Vector3 (
            0.0f,
            -gravity,
            0.0f
        );

    }

    void OnCollisionStay ( ) {

        isGrounded = true;

    }

    void ControlPlayer ( ) {

        moveHorizontal = Input.GetAxis ( "Horizontal" );
        moveVertical = Input.GetAxis ( "Vertical" );
        Debug.Log ( direction );

        Vector3 camForward = cam.transform.forward;
        camForward.y = 0.0f;

        Quaternion camRotationFlattened = Quaternion.LookRotation ( camForward );
        movementRotation = camRotationFlattened * movementRotation;

        if ( isGrounded == true ) {
            // Current movement
            rb.velocity = new Vector3 (
                moveHorizontal,
                0.0f,
                moveVertical
            ).normalized * speed;
        }
        else {
            rb.AddForce (
                movementRotation * speed * jumpModifier
            );
        }

        if ( Input.GetKey ( KeyCode.Space ) || Input.GetKey ( KeyCode.Joystick1Button1 ) && isGrounded ) {
            jumpHeight = ( jumpForce * jumpModifier );
            rb.velocity = new Vector3 (
                rb.velocity.x,
                jumpHeight,
                rb.velocity.z
            );
            isGrounded = false;
        }

        if ( movementRotation.sqrMagnitude > 0.1f && isGrounded ) {
            transform.rotation = Quaternion.Slerp (
                transform.rotation,
                Quaternion.LookRotation ( movementRotation ),
                10.0f
            );
        }

    }

    public void StickToWorldspace ( Transform root, Transform camera, ref float directionOut, ref float speedOut ) {

        Vector3 rootDirection = root.forward;

        Vector3 stickDirection = new Vector3 (
            moveHorizontal,
            0.0f,
            moveVertical
        );

        speedOut = stickDirection.sqrMagnitude;

        Vector3 CameraDirection = camera.forward;
        CameraDirection.y = 0.0f;

        Quaternion referentialShift = Quaternion.FromToRotation (
            rootDirection,
            Vector3.Normalize ( CameraDirection )
        );

        moveDirection = referentialShift * stickDirection;

        Vector3 axisSign = Vector3.Cross (
            moveDirection,
            rootDirection
        );

        // Will always face opposite to the camera
        Debug.DrawRay (
            new Vector3 (
                root.position.x,
                root.position.y + 5.0f,
                root.position.z
            ),
            moveDirection,
            Color.green
        );

        // Direction the player is facing
        Debug.DrawRay (
            new Vector3 (
                root.position.x,
                root.position.y + 5.0f,
                root.position.z
            ),
            rootDirection,
            Color.magenta
        );

        // Creates Angle between the two
        float angleRootToMove = Vector3.Angle (
            rootDirection,
            moveDirection
        );

        directionOut = angleRootToMove;
        Debug.Log ( directionOut );

    }

    void FixedUpdate ( ) {

        ControlPlayer ( );

        StickToWorldspace (
            this.transform,
            cam.transform,
            ref direction,
            ref speedPlus
        );

    }

}

Any help is most definitely appreciated!

Thank you & have a great evening!

I’d start by printing out what that force vector is you’re adding when not grounded. (top block of code)

Beyond that, to help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run?
  • what are the values of the variables involved? Are they initialized?

Knowing this information will help you reason about the behavior you are seeing.

yes, the code is running or i wouldn’t know the problem is happening… I already tried Debug logging. It just makes no sense.

Someone can help?

I had test run your script, its work for me

https://www.youtube.com/watch?v=BP9a8p4w9uA

1: I check the code

void OnCollisionStay()
    {

        isGrounded = true;

    }

this code here will make a huge mess if you don’t set up your Physic Layer properly, you may end up colliding with child objects

2: you may have flame rate problem.

you can give your Ground object a Tag call “Ground”
then
you can write this code

void OnCollisionStay(Collision collision)
    {
        if(collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
        }
    }

see if it make any different

I had this issue as well, I fixed it by setting the gravity in project settings to -30. Try it

AerionXI using

Quaternion camRotationFlattened = Quaternion.LookRotation ( camForward );
movementRotation = camRotationFlattened * movementRotation;

as gravity direction and I believe AerionXI’s rigidbody didn’t use gravity.
how ever I test it once with gravity turn off, but I keep going up in the air forever never come down.
I also debuged movementRotation, its always return 0,0,0.
its something about movementRotation that doesn’t work right.
so I change it to

if (isGrounded == true)
        {
            // Current movement
            rb.velocity = new Vector3(
                moveHorizontal,
                0.0f,
                moveVertical
            ).normalized * speed;
        }
        else
        {
            rb.AddForce(
                Vector3.down * speed * jumpModifier
            ); ;
        }

I fall down again but I jump very high because jumpModifier.
so I low it to 0.2 and I no long jump very high but I fall very slow
so I add public float jumpSpeed = 20; and use it

if (isGrounded == true)
        {
            // Current movement
            rb.velocity = new Vector3(
                moveHorizontal,
                0.0f,
                moveVertical
            ).normalized * speed;
        }
        else
        {
            rb.AddForce(
                Vector3.down * jumpSpeed
            );
        }

it worked, but I don’t know if this what AerionXI want
and again I really don’t know what is going on with movementRotation.

That didn’t work. The player is still slowly falling.

what is your setting?

Setting the gravity to -30 should work, in the project settings. It worked for me
EDIT: The gravity didn’t cause this. It works fine without even changing anything

@Putcho :

this is the script I used in video tell me does it behavior the same as in video?

https://www.youtube.com/watch?v=Ksrb4laixtA

using UnityEngine;

public class ThirdPersonMovement : MonoBehaviour
{

    [Header("Target{s}")]
    public Camera cam;
    public Rigidbody rb;

    [Header("Physics")]
    public float speed;
    public float jumpSpeed;
    public float jumpForce = 17.0f;
    public float gravity = 45.0f;
    public float jumpModifier = 2.0f;
    private float jumpHeight = 0.0f;
    private float directionSpeed = 3.0f;
    private float speedPlus = 0.0f;
    private float direction = 0.0f;

    [Header("Grounded Check { Unhidden }")]
    public bool isGrounded = true;

    [Header("Jump Vector3 { Unhidden }")]
    public Vector3 jump;

    private float moveHorizontal;
    private float moveVertical;

    private Vector3 movement;
    private Vector3 movementRotation;
    private Vector3 moveDirection;
    private Vector3 curLoc;
    private Vector3 prevLoc;

    void Awake()
    {

        cam = Camera.main; // GetComponent <Camera> ( )
        rb = GetComponent<Rigidbody>();
        jump = new Vector3(0.0f, 0.0f, 0.0f);

        Physics.gravity = new Vector3(
            0.0f,
            -gravity,
            0.0f
        );
    }

    //void OnCollisionStay()
    //{

    //    isGrounded = true;

    //}

    //private void OnTriggerStay(Collider other)
    //{
       
    //}

    void OnCollisionStay(Collision collision)
    {
        if(collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
        }
    }

    void ControlPlayer()
    {

        moveHorizontal = Input.GetAxis("Horizontal");
        moveVertical = Input.GetAxis("Vertical");
        Debug.Log(direction);

        Vector3 camForward = cam.transform.forward;

        camForward.y = 0.0f;

        Quaternion camRotationFlattened = Quaternion.LookRotation(camForward);

        movementRotation = camRotationFlattened * movementRotation;

        if (isGrounded == true)
        {
            // Current movement
            rb.velocity = new Vector3(
                moveHorizontal,
                0.0f,
                moveVertical
            ).normalized * speed;
        }
        else
        {
            rb.AddForce(
                Vector3.down * jumpSpeed
            );
        }

        if (Input.GetKey(KeyCode.Space) && isGrounded  || Input.GetKey(KeyCode.Joystick1Button1) && isGrounded)
        {
            jumpHeight = (jumpForce * jumpModifier);
            rb.velocity = new Vector3(
                rb.velocity.x,
                jumpHeight,
                rb.velocity.z
            );
            isGrounded = false;
        }

        if (movementRotation.sqrMagnitude > 0.1f && isGrounded)
        {
            transform.rotation = Quaternion.Slerp(
                transform.rotation,
                Quaternion.LookRotation(movementRotation),
                10.0f
            );
        }

    }

    public void StickToWorldspace(Transform root, Transform camera, ref float directionOut, ref float speedOut)
    {

        Vector3 rootDirection = root.forward;

        Vector3 stickDirection = new Vector3(
            moveHorizontal,
            0.0f,
            moveVertical
        );

        speedOut = stickDirection.sqrMagnitude;

        Vector3 CameraDirection = camera.forward;
        CameraDirection.y = 0.0f;

        Quaternion referentialShift = Quaternion.FromToRotation(
            rootDirection,
            Vector3.Normalize(CameraDirection)
        );

        moveDirection = referentialShift * stickDirection;

        Vector3 axisSign = Vector3.Cross(
            moveDirection,
            rootDirection
        );

        // Will always face opposite to the camera
        Debug.DrawRay(
            new Vector3(
                root.position.x,
                root.position.y + 5.0f,
                root.position.z
            ),
            moveDirection,
            Color.green
        );

        // Direction the player is facing
        Debug.DrawRay(
            new Vector3(
                root.position.x,
                root.position.y + 5.0f,
                root.position.z
            ),
            rootDirection,
            Color.magenta
        );

        // Creates Angle between the two
        float angleRootToMove = Vector3.Angle(
            rootDirection,
            moveDirection
        );

        directionOut = angleRootToMove;
        Debug.Log(directionOut);

    }

    void FixedUpdate()
    {

        ControlPlayer();

        StickToWorldspace(
            this.transform,
            cam.transform,
            ref direction,
            ref speedPlus
        );

    }

}

Yes, @Putcho , that is the same one. But it’s still only allowing for slow gravity when NOT jumping, but falling off something instead.

ah I see now, you are having ground check problem,. not gravity or jump

see the red line on the image that’s is the problem, i think. you need a better way to check the ground

1 Like

Oh ok, so then you should try for the ground check to make a new object under the player instead of the player itself

I don’t understand…

1 Like

You should get the ground check from another gameobject underneath the player, and edit the script to make that happen