求射线与三角形交点(C#代码Unity环境下测试通过)

上代码:

bool RayCrossTriAngle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3, out Vector3 point)
{
	point = Vector3.zero;

	Vector3 normal = Vector3.Cross(p2 - p1, p3 - p1);
	float t = -Vector3.Dot((ray.origin - p1), normal) / Vector3.Dot(ray.direction, normal);

	if (t < 0) return false;

	point = ray.origin + ray.direction * t;

	if (Vector3.Dot(Vector3.Cross(p1 - point, p2 - point), normal) < 0) return false;
	if (Vector3.Dot(Vector3.Cross(p2 - point, p3 - point), normal) < 0) return false;
	if (Vector3.Dot(Vector3.Cross(p3 - point, p1 - point), normal) < 0) return false;

	return true;
}

原理参考链接

你可能感兴趣的:(算法,算法,Unity)