Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Slope check not working correctly

Discussion in 'Scripting' started by Pixitales, Jan 15, 2020.

  1. Pixitales

    Pixitales

    Joined:
    Oct 24, 2018
    Posts:
    227
    Its a 3D game with character controller and I want to calculate the slope angle that the player is standing on. No rigidbody.

    I dont think my slope check is giving me the correct slope angles. On at 60 degree ramp i get 9.558E-11. If i touch the edge of that slope, it reads 80 degrees. On a low slope, it reads 1.45...E-11, if i touch the edge it says 60 degrees.

    Code (CSharp):
    1.    
    2.  
    3.     public LayerMask groundLayer;
    4.     [SerializeField] private float castLength;
    5.     [SerializeField] private bool isDebugMode = false;
    6.  
    7.     private Transform MyTransform;
    8.     private bool hasDetectedHit;
    9.     private Vector3 hitPosition;
    10.     private Vector3 hitNormal;
    11.     private float hitDistance;
    12.  
    13.   private void CastRay()
    14.     {
    15.         if (isDebugMode)
    16.         {
    17.             Debug.DrawRay(hitPosition, hitNormal, Color.red, Time.deltaTime);
    18.         }
    19.  
    20.         RaycastHit hit;
    21.         hasDetectedHit = Physics.Raycast(MyTransform.position, Vector3.down, out hit, castLength, groundLayer, QueryTriggerInteraction.Ignore);
    22.  
    23.         if (hasDetectedHit)
    24.         {
    25.             hitPosition = hit.point;
    26.             hitNormal = hit.normal;
    27.  
    28.             hitDistance = hit.distance;
    29.         }
    30.     }
    31.  
    32. public bool HasDetectedHit()
    33.     {
    34.         return hasDetectedHit;
    35.     }
    36.  
    37.     public Vector3 GetNormal()
    38.     {
    39.         return hitNormal;
    40.     }
    41.  
    42.     public float GetSlopeAngle()
    43.     {
    44.         if (!hasDetectedHit)
    45.         {
    46.             return 0;
    47.         }
    48.         else
    49.         {
    50.             float slopeAngle = Mathf.Atan2(hitNormal.x, hitNormal.y) * Mathf.Rad2Deg;
    51.  
    52.             return Mathf.Abs(slopeAngle);
    53.         }
    54.     }
     
  2. Pixitales

    Pixitales

    Joined:
    Oct 24, 2018
    Posts:
    227
    nvm i changed my calculation