Unity求射线与球体交点(有可能还能优化)

发布时间:2024年01月14日

代码如下:

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;
}

文章来源:https://blog.csdn.net/ttod/article/details/135580760
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。