Drawing a cube volume at a particular start/end point - best approach?
I want to create a realtime updated selection visualization in the form of a 3D cube volume to partition sections of the world defined by mouse click to set start point+drag to set size. The mouse handling is done, however the visualization part is what is causing me trouble. Essentially, I need to draw a 3D cube volume (w/an arbitrary height on the y axis) stretched between 2 corner points across the x/z axis, drawn with the mouse (from a top-down perspective).
I'm currently scaling a cube to try to simulate this effect, but the problem is the cube is stretching from its center point instead of the corners of the click/drag operation.
I apologize if this is ridiculously easy to do, but math (even in its simplest form) is not my strong point, and even if it was, I don't want to have to deal with the Unity quirks of constantly offsetting the position of the default cube while I scale it with my mouse if I can avoid it. Is there an easier way to setup the visualization of the cube volume, such as simply drawing a basic cube from a start/end corners directly, kind of like a gizmo?
Answer by awesomedata · Feb 07, 2017 at 10:14 PM
Sucks nobody could point me in the right direction on this... I don't mind answering my own question, but I would have thought there would be more knowledgeable people out there willing to share a few moments... :(
Anyway, for those like me looking for the right way to go about something like this, it turns out that using procedural meshes works great for stuff like this.
If you're new to procedural meshes, to start with, remember to use the "meshFilter.sharedMesh" instead of the "meshFilter.mesh" to display your new mesh in the scene view when the game is NOT running, otherwise you'll get leaks. Also, be sure to create a new mesh first, otherwise you'll end up replacing the mesh on the meshFilter or simply get a null value.
To get something like what I was after, you draw a few faces, then simply offset all the individual vertices on those faces however you need to.
When you're done defining everything, you call this stuff:
mesh.vertices = vertices;
mesh.normals = normals;
mesh.uv = uvs;
mesh.triangles = triangles;
mesh.RecalculateBounds();
mesh.Optimize();
When that's done, you're good to go, as your mesh filter will update automagically with your new verts, triangles, normals, etc., and your mesh will represent their new settings!
Procedural meshes -- demystified. :)