Search Unity

Question Applying downward force to a CharacterController while on slopes?

Discussion in 'Scripting' started by Henry_Gamer57, Feb 10, 2024.

  1. Henry_Gamer57

    Henry_Gamer57

    Joined:
    Jan 10, 2024
    Posts:
    15
    When I walk down slopes my player bounces and it results in the controller.isGrounded turning false repeatedly. My slope check code is a bit plain, I just use Vector3.Angle for the slope angle and then Vector3.dot for the player direction as well as my previous position to make sure the game is correctly checking if I am both facing up/down and moving uphill/downhill.

    I have tried to apply downward force using Vector3.down and also a different method to apply extra gravity if I am moving downhill, and visually everything looks fine and the bouncing is completely gone, but the isGrounded still turns false and true repeatedly. I put that code inside the if (slopeDot > 0) statement but it never does anything.

    Code (CSharp):
    1. // Update
    2. Vector3 movementDir = (transform.position - lastPos);
    3. lastPos = transform.position;
    4.  
    5. if (isGrounded)
    6. {
    7.     RaycastHit slopeTestHit;
    8.  
    9.     if (Physics.Raycast(transform.position, Vector3.down, out slopeTestHit, 2f))
    10.     {
    11.         float slopeAngle = Vector3.Angle(slopeTestHit.normal, Vector3.up);
    12.  
    13.         if (slopeAngle > 0 && slopeAngle < 65) // Within slope limit
    14.         {
    15.             Vector3 downhillDir = Vector3.ProjectOnPlane(Vector3.down, slopeTestHit.normal);
    16.  
    17.             float slopeDot = Vector3.Dot(movementDir, downhillDir);
    18.  
    19.             if (slopeDot > 0)
    20.             {
    21.                 // Going down
    22.             }
    23.             else if (slopeDot < 0)
    24.             {
    25.                 // Going up
    26.             }
    27.        }
    28.        else
    29.        {
    30.            // Flat surface, do nothing
    31.        }
    32.    }
    33. }
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,710
  3. Henry_Gamer57

    Henry_Gamer57

    Joined:
    Jan 10, 2024
    Posts:
    15