检测射线与球体交点数量代码实现(C#代码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,算法,算法,Unity)