Calculate UV at center of triangle.

I would like to iterate through the triangles of a mesh and grab the UV coordinate at or near the center of the triangle.

I’ve seen ways to convert a UV coordinate to a real world position, but do not understand how I could do it the other way around using the triangles.

Does this help

typical code …

function findUVForPaintUnderThisPoint(p:Vector3):Vector2
	// recall that by this stage, the ground mesh is finished
	p.y = HigherThanEverything;
	if ( Physics.Raycast( p,
		testHit, Mathf.Infinity, (1<<8) ) )
			return testHit.textureCoord;
	// crisis no uv found !!!

it’s common you have to sort of use raycasts for things, even where you think it has nothing to do with what you’re doing, heh !

Just TBC … note that it’s trivial to get the center point of a 3D, or, 2D triangle:

Just add the three coords, and divide by 3.0.


it’s kind of mentally bizarre but to get the center point, just do that to the three 3D coirds.

To get the UV at that same point, just do the same to the 2D UV coords !!

I’m pretty sure UV is linear within tris {but that could well be a “gotchya”} but in any event it would be pretty close, so you’re probably all set with that?

If you want the texture coordinate in the middle of the triangle, then do as Fattie suggested; Add the texture coordinates at the triangles vertices together and divide by three.

Raycasting is overkill for this sort of thing, unless you don’t already know which triangle you want.

For a more general solution I’d look into Barycentric coodinates Barycentric coordinate system - Wikipedia.