示例#1
0
        public bool Raycast(Ray ray, out float t)
        {
            t = 0.0f;

            // Calculate the coefficients of the quadratic equation
            Vector3 sphereCenterToRayOrigin = ray.origin - _center;
            float   a = Vector3.SqrMagnitude(ray.direction);
            float   b = 2.0f * Vector3.Dot(ray.direction, sphereCenterToRayOrigin);
            float   c = Vector3.SqrMagnitude(sphereCenterToRayOrigin) - _radius * _radius;

            // If we have a solution to the equation, the ray most likely intersects the sphere.
            float t1, t2;

            if (Equation.SolveQuadratic(a, b, c, out t1, out t2))
            {
                // Make sure the ray doesn't intersect the sphere only from behind
                if (t1 < 0.0f && t2 < 0.0f)
                {
                    return(false);
                }

                // Make sure we are using the smallest positive t value
                if (t1 < 0.0f)
                {
                    float temp = t1;
                    t1 = t2;
                    t2 = temp;
                }
                t = t1;

                return(true);
            }

            // If we reach this point it means the ray does not intersect the sphere in any way
            return(false);
        }