Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Issue with Gravity

Discussion in 'Scripting' started by AerionXI, Mar 26, 2021.

  1. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    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

    Code (CSharp):
    1.  
    2. if ( isGrounded == true ) {
    3.     // Current movement
    4.     rb.velocity = new Vector3 (
    5.         moveHorizontal,
    6.         0.0f,
    7.         moveVertical
    8.     ).normalized * speed;
    9. }
    10. else {
    11.     rb.AddForce (
    12.         movementRotation * speed * jumpModifier
    13.     );
    14. }
    15.  
    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 :

    Code (CSharp):
    1.  
    2. void ControlPlayer ( ) {
    3.     moveHorizontal = Input.GetAxis ( "Horizontal" );
    4.     moveVertical = Input.GetAxis ( "Vertical" );
    5.     Debug.Log ( direction );
    6.     Vector3 camForward = cam.transform.forward;
    7.     camForward.y = 0.0f;
    8.     Quaternion camRotationFlattened = Quaternion.LookRotation ( camForward );
    9.     movementRotation = camRotationFlattened * movementRotation;
    10.     if ( isGrounded == true ) {
    11.         // Current movement
    12.         rb.velocity = new Vector3 (
    13.             moveHorizontal,
    14.             0.0f,
    15.             moveVertical
    16.         ).normalized * speed;
    17.     }
    18.     else {
    19.         rb.AddForce (
    20.             movementRotation * speed * jumpModifier
    21.         );
    22.     }
    23.     if ( Input.GetKey ( KeyCode.Space ) || Input.GetKey ( KeyCode.Joystick1Button1 ) && isGrounded ) {
    24.         jumpHeight = ( jumpForce * jumpModifier );
    25.         rb.velocity = new Vector3 (
    26.             rb.velocity.x,
    27.             jumpHeight,
    28.             rb.velocity.z
    29.         );
    30.         isGrounded = false;
    31.     }
    32.     if ( movementRotation.sqrMagnitude > 0.1f && isGrounded ) {
    33.         transform.rotation = Quaternion.Slerp (
    34.             transform.rotation,
    35.             Quaternion.LookRotation ( movementRotation ),
    36.             10.0f
    37.         );
    38.     }
    39. }
    40.  
    Here's the whole script :

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public class ThirdPersonMovement : MonoBehaviour {
    5.  
    6.     [ Header ( "Target{s}" ) ]
    7.     public Camera cam;
    8.     public Rigidbody rb;
    9.  
    10.     [ Header ( "Physics" ) ]
    11.     public float speed;
    12.     public float jumpForce = 17.0f;
    13.     public float gravity = 45.0f;
    14.     public float jumpModifier = 2.0f;
    15.     private float jumpHeight = 0.0f;
    16.     private float directionSpeed = 3.0f;
    17.     private float speedPlus = 0.0f;
    18.     private float direction = 0.0f;
    19.  
    20.     [ Header ( "Grounded Check { Unhidden }" ) ]
    21.     public bool isGrounded = true;
    22.  
    23.     [ Header ( "Jump Vector3 { Unhidden }" ) ]
    24.     public Vector3 jump;
    25.  
    26.     private float moveHorizontal;
    27.     private float moveVertical;
    28.  
    29.     private Vector3 movement;
    30.     private Vector3 movementRotation;
    31.     private Vector3 moveDirection;
    32.     private Vector3 curLoc;
    33.     private Vector3 prevLoc;
    34.  
    35.     void Awake ( ) {
    36.  
    37.         cam = Camera.main; // GetComponent <Camera> ( )
    38.         rb = GetComponent <Rigidbody> ( );
    39.         jump = new Vector3 ( 0.0f, 0.0f, 0.0f );
    40.  
    41.         Physics.gravity = new Vector3 (
    42.             0.0f,
    43.             -gravity,
    44.             0.0f
    45.         );
    46.  
    47.     }
    48.  
    49.     void OnCollisionStay ( ) {
    50.  
    51.         isGrounded = true;
    52.  
    53.     }
    54.  
    55.     void ControlPlayer ( ) {
    56.  
    57.         moveHorizontal = Input.GetAxis ( "Horizontal" );
    58.         moveVertical = Input.GetAxis ( "Vertical" );
    59.         Debug.Log ( direction );
    60.  
    61.         Vector3 camForward = cam.transform.forward;
    62.         camForward.y = 0.0f;
    63.  
    64.         Quaternion camRotationFlattened = Quaternion.LookRotation ( camForward );
    65.         movementRotation = camRotationFlattened * movementRotation;
    66.  
    67.         if ( isGrounded == true ) {
    68.             // Current movement
    69.             rb.velocity = new Vector3 (
    70.                 moveHorizontal,
    71.                 0.0f,
    72.                 moveVertical
    73.             ).normalized * speed;
    74.         }
    75.         else {
    76.             rb.AddForce (
    77.                 movementRotation * speed * jumpModifier
    78.             );
    79.         }
    80.  
    81.         if ( Input.GetKey ( KeyCode.Space ) || Input.GetKey ( KeyCode.Joystick1Button1 ) && isGrounded ) {
    82.             jumpHeight = ( jumpForce * jumpModifier );
    83.             rb.velocity = new Vector3 (
    84.                 rb.velocity.x,
    85.                 jumpHeight,
    86.                 rb.velocity.z
    87.             );
    88.             isGrounded = false;
    89.         }
    90.  
    91.         if ( movementRotation.sqrMagnitude > 0.1f && isGrounded ) {
    92.             transform.rotation = Quaternion.Slerp (
    93.                 transform.rotation,
    94.                 Quaternion.LookRotation ( movementRotation ),
    95.                 10.0f
    96.             );
    97.         }
    98.  
    99.     }
    100.  
    101.     public void StickToWorldspace ( Transform root, Transform camera, ref float directionOut, ref float speedOut ) {
    102.  
    103.         Vector3 rootDirection = root.forward;
    104.  
    105.         Vector3 stickDirection = new Vector3 (
    106.             moveHorizontal,
    107.             0.0f,
    108.             moveVertical
    109.         );
    110.  
    111.         speedOut = stickDirection.sqrMagnitude;
    112.  
    113.         Vector3 CameraDirection = camera.forward;
    114.         CameraDirection.y = 0.0f;
    115.  
    116.         Quaternion referentialShift = Quaternion.FromToRotation (
    117.             rootDirection,
    118.             Vector3.Normalize ( CameraDirection )
    119.         );
    120.  
    121.         moveDirection = referentialShift * stickDirection;
    122.  
    123.         Vector3 axisSign = Vector3.Cross (
    124.             moveDirection,
    125.             rootDirection
    126.         );
    127.  
    128.         // Will always face opposite to the camera
    129.         Debug.DrawRay (
    130.             new Vector3 (
    131.                 root.position.x,
    132.                 root.position.y + 5.0f,
    133.                 root.position.z
    134.             ),
    135.             moveDirection,
    136.             Color.green
    137.         );
    138.  
    139.         // Direction the player is facing
    140.         Debug.DrawRay (
    141.             new Vector3 (
    142.                 root.position.x,
    143.                 root.position.y + 5.0f,
    144.                 root.position.z
    145.             ),
    146.             rootDirection,
    147.             Color.magenta
    148.         );
    149.  
    150.         // Creates Angle between the two
    151.         float angleRootToMove = Vector3.Angle (
    152.             rootDirection,
    153.             moveDirection
    154.         );
    155.  
    156.         directionOut = angleRootToMove;
    157.         Debug.Log ( directionOut );
    158.  
    159.     }
    160.  
    161.     void FixedUpdate ( ) {
    162.  
    163.         ControlPlayer ( );
    164.  
    165.         StickToWorldspace (
    166.             this.transform,
    167.             cam.transform,
    168.             ref direction,
    169.             ref speedPlus
    170.         );
    171.  
    172.     }
    173.  
    174. }
    175.  
    Any help is most definitely appreciated!

    Thank you & have a great evening!
     
    Last edited: Mar 26, 2021
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    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.
     
  3. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    yes, the code is running or i wouldn't know the problem is happening... I already tried Debug logging. It just makes no sense.
     
    Last edited: Mar 26, 2021
  4. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    Someone can help?
     
  5. Putcho

    Putcho

    Joined:
    Jun 1, 2013
    Posts:
    246
    I had test run your script, its work for me



    1: I check the code
    Code (CSharp):
    1.  
    2. void OnCollisionStay()
    3.     {
    4.  
    5.         isGrounded = true;
    6.  
    7.     }
    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.
     
  6. Putcho

    Putcho

    Joined:
    Jun 1, 2013
    Posts:
    246
    you can give your Ground object a Tag call "Ground"
    then
    you can write this code
    Code (CSharp):
    1.  
    2. void OnCollisionStay(Collision collision)
    3.     {
    4.         if(collision.gameObject.CompareTag("Ground"))
    5.         {
    6.             isGrounded = true;
    7.         }
    8.     }
    see if it make any different
     
  7. jasonasaad2

    jasonasaad2

    Joined:
    Nov 30, 2020
    Posts:
    51
    I had this issue as well, I fixed it by setting the gravity in project settings to -30. Try it
     
  8. Putcho

    Putcho

    Joined:
    Jun 1, 2013
    Posts:
    246
    AerionXI using
    Code (CSharp):
    1.  
    2. Quaternion camRotationFlattened = Quaternion.LookRotation ( camForward );
    3. 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
    Code (CSharp):
    1.  
    2. if (isGrounded == true)
    3.         {
    4.             // Current movement
    5.             rb.velocity = new Vector3(
    6.                 moveHorizontal,
    7.                 0.0f,
    8.                 moveVertical
    9.             ).normalized * speed;
    10.         }
    11.         else
    12.         {
    13.             rb.AddForce(
    14.                 Vector3.down * speed * jumpModifier
    15.             ); ;
    16.         }
    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

    Code (CSharp):
    1.  
    2. if (isGrounded == true)
    3.         {
    4.             // Current movement
    5.             rb.velocity = new Vector3(
    6.                 moveHorizontal,
    7.                 0.0f,
    8.                 moveVertical
    9.             ).normalized * speed;
    10.         }
    11.         else
    12.         {
    13.             rb.AddForce(
    14.                 Vector3.down * jumpSpeed
    15.             );
    16.         }
    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.
     
  9. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    That didn't work. The player is still slowly falling.
     
  10. Putcho

    Putcho

    Joined:
    Jun 1, 2013
    Posts:
    246
    what is your setting?
     
  11. jasonasaad2

    jasonasaad2

    Joined:
    Nov 30, 2020
    Posts:
    51
    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
     
  12. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
  13. Putcho

    Putcho

    Joined:
    Jun 1, 2013
    Posts:
    246
    this is the script I used in video tell me does it behavior the same as in video?





    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class ThirdPersonMovement : MonoBehaviour
    4. {
    5.  
    6.     [Header("Target{s}")]
    7.     public Camera cam;
    8.     public Rigidbody rb;
    9.  
    10.     [Header("Physics")]
    11.     public float speed;
    12.     public float jumpSpeed;
    13.     public float jumpForce = 17.0f;
    14.     public float gravity = 45.0f;
    15.     public float jumpModifier = 2.0f;
    16.     private float jumpHeight = 0.0f;
    17.     private float directionSpeed = 3.0f;
    18.     private float speedPlus = 0.0f;
    19.     private float direction = 0.0f;
    20.  
    21.     [Header("Grounded Check { Unhidden }")]
    22.     public bool isGrounded = true;
    23.  
    24.     [Header("Jump Vector3 { Unhidden }")]
    25.     public Vector3 jump;
    26.  
    27.     private float moveHorizontal;
    28.     private float moveVertical;
    29.  
    30.     private Vector3 movement;
    31.     private Vector3 movementRotation;
    32.     private Vector3 moveDirection;
    33.     private Vector3 curLoc;
    34.     private Vector3 prevLoc;
    35.  
    36.     void Awake()
    37.     {
    38.  
    39.         cam = Camera.main; // GetComponent <Camera> ( )
    40.         rb = GetComponent<Rigidbody>();
    41.         jump = new Vector3(0.0f, 0.0f, 0.0f);
    42.  
    43.         Physics.gravity = new Vector3(
    44.             0.0f,
    45.             -gravity,
    46.             0.0f
    47.         );
    48.     }
    49.  
    50.     //void OnCollisionStay()
    51.     //{
    52.  
    53.     //    isGrounded = true;
    54.  
    55.     //}
    56.  
    57.     //private void OnTriggerStay(Collider other)
    58.     //{
    59.        
    60.     //}
    61.  
    62.     void OnCollisionStay(Collision collision)
    63.     {
    64.         if(collision.gameObject.CompareTag("Ground"))
    65.         {
    66.             isGrounded = true;
    67.         }
    68.     }
    69.  
    70.     void ControlPlayer()
    71.     {
    72.  
    73.         moveHorizontal = Input.GetAxis("Horizontal");
    74.         moveVertical = Input.GetAxis("Vertical");
    75.         Debug.Log(direction);
    76.  
    77.         Vector3 camForward = cam.transform.forward;
    78.  
    79.         camForward.y = 0.0f;
    80.  
    81.         Quaternion camRotationFlattened = Quaternion.LookRotation(camForward);
    82.  
    83.         movementRotation = camRotationFlattened * movementRotation;
    84.  
    85.         if (isGrounded == true)
    86.         {
    87.             // Current movement
    88.             rb.velocity = new Vector3(
    89.                 moveHorizontal,
    90.                 0.0f,
    91.                 moveVertical
    92.             ).normalized * speed;
    93.         }
    94.         else
    95.         {
    96.             rb.AddForce(
    97.                 Vector3.down * jumpSpeed
    98.             );
    99.         }
    100.  
    101.         if (Input.GetKey(KeyCode.Space) && isGrounded  || Input.GetKey(KeyCode.Joystick1Button1) && isGrounded)
    102.         {
    103.             jumpHeight = (jumpForce * jumpModifier);
    104.             rb.velocity = new Vector3(
    105.                 rb.velocity.x,
    106.                 jumpHeight,
    107.                 rb.velocity.z
    108.             );
    109.             isGrounded = false;
    110.         }
    111.  
    112.         if (movementRotation.sqrMagnitude > 0.1f && isGrounded)
    113.         {
    114.             transform.rotation = Quaternion.Slerp(
    115.                 transform.rotation,
    116.                 Quaternion.LookRotation(movementRotation),
    117.                 10.0f
    118.             );
    119.         }
    120.  
    121.     }
    122.  
    123.     public void StickToWorldspace(Transform root, Transform camera, ref float directionOut, ref float speedOut)
    124.     {
    125.  
    126.         Vector3 rootDirection = root.forward;
    127.  
    128.         Vector3 stickDirection = new Vector3(
    129.             moveHorizontal,
    130.             0.0f,
    131.             moveVertical
    132.         );
    133.  
    134.         speedOut = stickDirection.sqrMagnitude;
    135.  
    136.         Vector3 CameraDirection = camera.forward;
    137.         CameraDirection.y = 0.0f;
    138.  
    139.         Quaternion referentialShift = Quaternion.FromToRotation(
    140.             rootDirection,
    141.             Vector3.Normalize(CameraDirection)
    142.         );
    143.  
    144.         moveDirection = referentialShift * stickDirection;
    145.  
    146.         Vector3 axisSign = Vector3.Cross(
    147.             moveDirection,
    148.             rootDirection
    149.         );
    150.  
    151.         // Will always face opposite to the camera
    152.         Debug.DrawRay(
    153.             new Vector3(
    154.                 root.position.x,
    155.                 root.position.y + 5.0f,
    156.                 root.position.z
    157.             ),
    158.             moveDirection,
    159.             Color.green
    160.         );
    161.  
    162.         // Direction the player is facing
    163.         Debug.DrawRay(
    164.             new Vector3(
    165.                 root.position.x,
    166.                 root.position.y + 5.0f,
    167.                 root.position.z
    168.             ),
    169.             rootDirection,
    170.             Color.magenta
    171.         );
    172.  
    173.         // Creates Angle between the two
    174.         float angleRootToMove = Vector3.Angle(
    175.             rootDirection,
    176.             moveDirection
    177.         );
    178.  
    179.         directionOut = angleRootToMove;
    180.         Debug.Log(directionOut);
    181.  
    182.     }
    183.  
    184.     void FixedUpdate()
    185.     {
    186.  
    187.         ControlPlayer();
    188.  
    189.         StickToWorldspace(
    190.             this.transform,
    191.             cam.transform,
    192.             ref direction,
    193.             ref speedPlus
    194.         );
    195.  
    196.     }
    197.  
    198. }
    199.  
     
  14. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    Yes, @Putcho, that is the same one. But it's still only allowing for slow gravity when NOT jumping, but falling off something instead.
     
  15. Putcho

    Putcho

    Joined:
    Jun 1, 2013
    Posts:
    246
    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
     
    jasonasaad2 likes this.
  16. jasonasaad2

    jasonasaad2

    Joined:
    Nov 30, 2020
    Posts:
    51
    Oh ok, so then you should try for the ground check to make a new object under the player instead of the player itself
     
  17. AerionXI

    AerionXI

    Joined:
    Jul 20, 2020
    Posts:
    482
    I don't understand.....
     
    jasonasaad2 likes this.
  18. jasonasaad2

    jasonasaad2

    Joined:
    Nov 30, 2020
    Posts:
    51
    You should get the ground check from another gameobject underneath the player, and edit the script to make that happen