I created a float method that shoots raycasts in two different directions under the player to return the angle of the slope the player is standing on.
The groundCheck is a game object inside the lower part of the player. The groundMask is a layer mask with only the Ground layer selected. I already checked to make sure the player and the groundCheck are not ground layered.
private float CalculateGroundSlopeAngle()
{
if (!isGrounded) return 0f;
else
{
Ray ray1 = new Ray(groundCheck.transform.position, Vector3.down);
Ray ray2 = new Ray(groundCheck.transform.position, Vector3.down + Vector3.forward * 0.2f);
RaycastHit ray1hit, ray2hit;
Physics.Raycast(ray1, out ray1hit, 1f, groundMask);
Physics.Raycast(ray2, out ray2hit, 1f, groundMask);
Vector3 point1 = ray1hit.point;
Vector3 point2 = ray2hit.point;
Vector3 point3 = new Vector3(point2.x, point1.y, point2.z);
float adjacent = Vector3.Distance(point1, point3);
float opposite = Vector3.Distance(point2, point3);
float slopeAngle = Mathf.Rad2Deg * Mathf.Atan(opposite / adjacent);
Debug.Log("Ray1 Hit Point: " + point1);
Debug.Log("Ray2 Hit Point: " + point2);
Debug.Log("Right Triangle Point: " + point3);
Debug.Log("Adjacent: " + adjacent);
Debug.Log("Opposite: " + opposite);
return slopeAngle;
}
}
When the code is executed, ray1hit.point shows correct results (as far as I know), however ray2hit.point does not; rather, it is the exact same value as ray1hit.point. This messes up the rest of the code and doesn’t return the correct angle.