World position from UV coordinates.

I have been working with RaycastHit.textureCoord and find it to be very useful, but I was wondering if there was a way to access a world position (and rotation) from the mesh uvs directly? I would like to be able to use the uvs of a character as attach points for other objects and was wondering what the best way of going about this was?

Any input is appreciated, thanks!

I remember needing to do this once for a project, and I recall it being pretty complicated. If I recall correctly, you need the triangle you hit as well as the UV coordinates. Then you need to use barycentric interpolation, which essentially allows you to calculate a precise position within that triangle. I think raycast actually does barycentric interpolation for you, so the functionality might already be in Unity somewhere.

Now you seem to want to be able to do that without having the triangle, if I’m correct, yes? I don’t see any way of doing that without manually iterating through every triangle in the mesh. For one thing, UV mapping is not exclusive. One particular UV point could be mapped to more than one triangle. Indeed, if you’re wanting to use it to place things, you might even intend to use it that way.

Having said that, if you only need to do this thing once, perhaps iterating through all the triangles would be acceptable for you. It might even be something you could do with an editor script rather than a game script? If you go this way, I’d recommend reading up on barycentric coordinates and interpolation, because I’m not good enough at the complicated maths to be explaining it to you.

I don’t see how you could do that. Unless you had a special case, it doesn’t seem tp make sense conceptually. UV’s don’t logically map to a point in world space - and a point doesn’t have a rotation.

For example, one point in uv space could exist many times in world space.

Thanks for the replies, the uvs I am dealing with are very specific and are setup in such a way as to minimize duplication in world space and even then I am looking at more of a best case rather then pixel perfect accuracy. I will see if iterating over the triangles and uvs brings and setting up a system to compare that with the normal and set up the barycentric interpolation of those values.

The RaycastHit returns the point in world space where the ray struck the object. If you call Transform.InverseTransformDirection on the target object’s transform, you will get the contact point in the object’s local space. You should be able to use that as an attachment point (say if you want an arrow to stick out of a moving target at the point where it hit).