本文主要是介绍Unity检测射线与球体交点数量代码实现(可能是最简单最高效的),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
上代码:
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;
}
原理参考链接
这篇关于Unity检测射线与球体交点数量代码实现(可能是最简单最高效的)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!