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