- Home /
Create planar UVs on procedurally generated mesh
I have a completly flat 2D mesh that is being generated procedurally. ( more info here http://forum.unity3d.com/threads/181596-Triangulation-of-spline-to-mesh-questions-and-results )
The mesh was generated from this image that I'm now trying to apply as a texture, so I'm trying to get the UV's to work.
Vector2[] endingUVs = new Vector2[finalVerts.Count];
Bounds bounds = newMesh.bounds;
for(int k = 0; k < fVerts.Length;k++) {
Vector2 aUV = new Vector2((fVerts[k].x/bounds.size.y)*-1, (fVerts[k].y/bounds.size.y));
endingUVs[k] = aUV;
}
newMesh.uv = endingUVs;
Here are things I have found out:
Dividing by bounds.size.Y both times gives me the closest size at the correct aspect ratio (my image isn't quite square 492w*470h)
Multiplying by -1 gives me the right flip on the X axis
Afterward setting the offset to .5 and .5 in the editor makes it centered. (like below, at offset 0, 0 its in the top right)
Any ideas how I can get this sized correctly in a procedural way that will work for any image?
If I print out the values of some of the UV's I'm making I am getting some negative ones because naturally some of the vertices have negative positions. (0.3, -0.2) etc, when I try Math.Abs on the values that doesn't seem to give the desired results either.
Also I found this which is very similar code to what I have: http://docs.unity3d.com/Documentation/ScriptReference/Mesh-bounds.html
Answer by dchen05 · May 21, 2013 at 03:03 AM
Figured it out, ignore my rambling above. It turns out I was using the wrong bounds. The
The newly generated mesh had a tighter bounds, thus I was getting a smaller projection of the image, which makes sense.
What I wanted to use was the bounds of the original plane (not pictured here), which is the same size as my character texture, and makes for a correct planar projection. Awesome.
So yeah I was second guessing it, but the formula found here is pretty sound, just make sure you use the right bounds :) http://docs.unity3d.com/Documentation/ScriptReference/Mesh-bounds.html
Your answer
Follow this Question
Related Questions
Manual UV-Mapping of a Primitive Cube 1 Answer
Easy way to convert a bunch of vertices to triangles or uv's? 1 Answer
Scale mesh but keep original uv? 0 Answers
Check if a mesh has UV map at runtime 1 Answer
Procedural Mesh UVing 2 Answers