代码如下:
bool RayCrossSphere(Ray ray, Sphere sphere, out Vector3[] vs)
{
Vector3 c2o = sphere.center - ray.origin;
float sqrtRadius = sphere.radius * sphere.radius;
Vector3 project = Vector3.Project(c2o, ray.direction);
Vector3 vPoint = ray.origin + project;
Vector3 v2c = vPoint - sphere.center;
//
vs = new Vector3[] { };
if (c2o.sqrMagnitude <= sqrtRadius)
{
float lenVPoint2Surface = Mathf.Sqrt(sqrtRadius - v2c.sqrMagnitude);
vs = new Vector3[] { vPoint + ray.direction * lenVPoint2Surface };
return true;
}
else
{
if (Vector3.Dot(project, ray.direction) > 0)
{
float centerToRaySubRadius = sqrtRadius - v2c.sqrMagnitude;
if (Mathf.Approximately(centerToRaySubRadius, 0))
{
vs = new Vector3[] { vPoint };
}
else if (centerToRaySubRadius > 0)
{
float vDist = Mathf.Sqrt(centerToRaySubRadius);
float v2o = (vPoint - ray.origin).magnitude;
vs = new Vector3[] { ray.origin + ray.direction * (v2o - vDist), ray.origin + ray.direction * (v2o + vDist) };
}
}
}
return false;
}
补充球体类:
public class Sphere
{
public Vector3 center;
public float radius;
}