- Home /
Calculate UV-coordinates based on known vertices and their respective UVs
A (probably simple) question, but after hours of thinking, i barely can wrap my mind around it anymore. Short: i am stuck.
Background: i am developing a small feature to cut one mesh into two new meshes at runtime, using a customizable plane. This works well so far. Method is: create two copys of the original mesh and "collapse" the vertices, which are on the off-side of the plane relative to the new meshes side, onto the plane. The method is not part of the question, its just background information. For this method to look nice and clean, i have to recalculate some UV-coodrinates in the cut-process and thats were things get tricky.
Consider the following: I have a minimalistic mesh, containing 3 Vector3s A, B and C, forming a single triangle in 3D-space (see image below). Their respective world- and UV-coordinates are known. A 4. Vector3 D is calculated at runtime, its coordinates (world coordinates, as well as distance to A, B and C) are known. This new Vector3 D is guaranteed to be on the plane, which is spun up by A, B and C. The only thing unknown is the UV-coordinates of D, which have to be relative to the distance of D to A, B and C.
Question: How do I calculate the UV-coordinates of D (relative to A, B and C) using the Positions of A, B, C and D, UV-Coordinates of A, B and C and the Distances AD, BD and CD?
Answer by Bunny83 · Jul 06, 2017 at 05:45 PM
You can use my Barycentric struct(download). Just pass in the 3 vertex positions and the point inside the triangle. Then you can use Interpolate to interpolate the UV coordinates based on the barycentric coordinates:
var b = new Barycentric(A, B, C, D);
Vector2 uv_D = b.Interpolate(uv_A, uv_B, uv_C);
You can use the barycentric coordinates to interpolate any vertex attribute.
edit
I forgot that i also added that script to the unity wiki. In case the DB link above doesn't work anymore, see here on the wiki (Barycentric)
Used your code and tested it. Works like a charm! UV-coordinates of D are calculated perfectly using your snippet. Fast, understandable and easy-to-use answer. $$anonymous$$any thanks!
$$anonymous$$aybe you could also add the Barycentric-code as part of your answer, so the post becomes more persistent (since Dropbox-links tend to get lost over the years, whenever the free dropbox-space becomes critical).
Yes, I just realised that i already added the script to the wiki (Dec. 2015). I added the wiki link to my answer.
Your answer

Follow this Question
Related Questions
Assigning UV Map to model at runtime 0 Answers
unity Vector2 problem 1 Answer
Procedural Uniform UVs On a Plane 2 Answers
conserve momentum of vector3.moveTowards in 2D game 0 Answers
Wrong import of UV from blender 1 Answer