上代码:
int RayCrossSphere(Ray ray, Sphere sphere)
{Vector3 originT0Center = sphere.center - ray.origin;float sqrtRadius = sphere.radius * sphere.radius;if (originT0Center.sqrMagnitude <= sqrtRadius){return 1;}else{Vector3 project = Vector3.Project(originT0Center, ray.direction);if (Vector3.Dot(project, ray.direction) < 0){return 0;}else{Vector3 vPoint = ray.origin + project;float centerToRaySubRadius = (vPoint - sphere.center).sqrMagnitude - sqrtRadius;if (centerToRaySubRadius > 0){return 0;}else if (Mathf.Approximately(centerToRaySubRadius, 0)){return 1;}else{return 2;}}}
}
球体类补充:
public class Sphere
{public Vector3 center;public float radius;
}
原理参考链接