在网格上获取UV对应的射线

发布时间:2024年01月11日

?代码参考如下:

using UnityEngine;

public class Calculate
{
	public static bool GetRayByUV(Mesh mesh, Vector2 uv,out Ray ray)
	{
		int[] ts = mesh.triangles;
		Vector2[] uvs = mesh.uv;
		Vector3[] vs = mesh.vertices;
		Vector3[] ns = mesh.normals;
		ray = new Ray();
		for (int i = 0; i < ts.Length; i += 3)
		{
			Vector2 u1 = uvs[ts[i]];
			Vector2 u2 = uvs[ts[i + 1]];
			Vector2 u3 = uvs[ts[i + 2]];

			float c = Cross(u1, u2, u3); 
			if (Mathf.Approximately(c, 0)) continue;

			float c1 = Cross(u2, u3, uv) / c; 
			if (c1 < 0) continue;
			float c2 = Cross(u3, u1, uv) / c; 
			if (c2 < 0) continue;
			float c3 = Cross(u1, u2, uv) / c; 
			if (c3 < 0) continue;

			ray.direction = (ns[ts[i]] + ns[ts[i + 1]] + ns[ts[i + 2]]) / 3f;
			ray.origin = c1 * vs[ts[i]] + c2 * vs[ts[i + 1]] + c3 * vs[ts[i + 2]];

			return true;
		}
		return false;
	}

	static float Cross(Vector2 p1, Vector2 p2, Vector2 p3)
	{
		Vector2 v1 = p1 - p3;
		Vector2 v2 = p2 - p3;
		return v1.x * v2.y - v1.y * v2.x;
	}
}

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