上代码:
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;
}

本文介绍了如何使用C#编写了一个名为`intRayCrossSphere`的函数,用于计算给定的Ray(光线)与Sphere(球体)的交点情况,包括是否相交、交点类型。同时提供了球体类`Sphere`的结构和参考链接。
382

被折叠的 条评论
为什么被折叠?



