Esempio n. 1
0
    // Real-time Collision Detection, p179.
    public float RayCast(Vector3 from, Vector3 to, float maxFraction = 1.0f)
    {
        float tMin = float.MinValue;
        float tMax = float.MaxValue;

        Vector3 d    = to - from;
        Vector3 absD = VectorUtil.Abs(d);

        for (int i = 0; i < 3; ++i)
        {
            float dComp    = VectorUtil.GetComopnent(d, i);
            float absDComp = VectorUtil.GetComopnent(absD, i);
            float fromComp = VectorUtil.GetComopnent(from, i);
            float minComp  = VectorUtil.GetComopnent(Min, i);
            float maxComp  = VectorUtil.GetComopnent(Max, i);

            if (absDComp < float.Epsilon)
            {
                // parallel?
                if (fromComp < minComp || maxComp < fromComp)
                {
                    return(float.MinValue);
                }
            }
            else
            {
                float invD = 1.0f / dComp;
                float t1   = (minComp - fromComp) * invD;
                float t2   = (maxComp - fromComp) * invD;

                if (t1 > t2)
                {
                    float temp = t1;
                    t1 = t2;
                    t2 = temp;
                }

                tMin = Mathf.Max(tMin, t1);
                tMax = Mathf.Min(tMax, t2);

                if (tMin > tMax)
                {
                    return(float.MinValue);
                }
            }
        }

        // does the ray start inside the box?
        // does the ray intersect beyond the max fraction?
        if (tMin < 0.0f || maxFraction < tMin)
        {
            return(float.MinValue);
        }

        // intersection detected
        return(tMin);
    }