Programmatic Meshes, pt. I

I’m not sure how many parts this will end up being, but I’ve been spending a good amount of time lately on programmatically generating both 2D and 3D meshes. Currently, I’m working on a library to expand the Unity primitives system to create meshes based on parameters. So far, I’ve built Quads (standard/two triangle, starburst array from center), Circles (starburst), Hexagons (starburst, compact), and Triangles (equilateral, right). I’m now working on basic spheres from sets of circles.

Single Circle
Single Circle
Sphere from circles
Sphere from circles

One thing that these shapes do, so long as the shape object is kept, is track vertices across changes. I’d like to do some basic deformation options down the road, but for now this works well because for the sphere, I create just a single circle, copy its vertex[] rotate it and copy over and over until it’s complete.

The above image, “Sphere from circles” is actually just multiple circle objects rotated properly. My current speedbump is sorting the vertices for the sphere itself. The vertex at (0, 0, 0) is removed, and the vertices where x=0 are only parsed from the first circle rotation. All vertices are then ordered descending by y, so from the top down. Now I need to also sort the x/z values in clockwise order so that the vertex[] basically stores the vertices as horizontal slices from top to bottom, then clockwise for each slice (or counter-clockwise). This is necessary so that the triangles can also be generated programmatically without intervention.

My current attempt was something like this:

this.vertices = vertList.OrderByDescending(o => o.y).ThenBy(o => Mathf.Atan2(o.x, o.z)).ToArray();

But that doesn’t properly sort the x/z components. I’m sure there’s an easy formula that I’m missing, so… I’ll have to keep working through it.

One thought on “Programmatic Meshes, pt. I”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.