?代码参考如下:
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;
}
}