using UnityEngine;

namespace pdinklag.CPW.Common
{
    public static class Ground
    {
        private static readonly int GROUND_LAYERS = 0x10C00;

        /// <summary>
        /// Casts the vector to the ground.
        /// 
        /// This performs a raycast from above the given vector (by scanDistance)
        /// down by twice the scanDistance, and reports the hit position if any.
        /// </summary>
        /// <param name="v">the vector</param>
        /// <param name="scanDistance">the maximum distance to scan for ground</param>
        /// <returns>the position on the ground, or the input vector if no ground was found</returns>
        public static Vector3 OnGround(this Vector3 v, float scanDistance = 0.5f)
        {
            if (Physics.Raycast(
                new Ray(v + scanDistance * Vector3.up, Vector3.down),
                out var hit,
                2.0f * scanDistance,
                GROUND_LAYERS,
                QueryTriggerInteraction.Ignore))
            {

                return hit.point;
            }
            else
            {
                return v;
            }
        }
    }
}
