Rotating an object around the centre of its mesh, using Quarternion AxisAngle

I’m working on a legacy project made entirely by someone else.

A group of objects called “surfaces” are instantiated using data from a JSON file. The meshes assigned to these objects are generated procedurally, so from what I can tell, the rotation origin is offset by a different amount for every object.

If I use RotateAround, with the point being the center of the mesh, the Euler rotation produces completely the wrong set of rotations, but in the right position.

Using Quaternion.AxisAngle produces the correct rotations, but in the wrong position.

Using the rotation tool in the editor at runtime produces perfect results, as the tool seems to know to take the center of the mesh as the origin for rotation, and simply translates the object to compensate.

Is there a way to replicate what the Editor rotation tool is doing in a script?

So, I see a few ways that I might try to approach this problem. The best way to do it is going to depend a lot on your application and the geometry you’re creating.

  1. Cheat: Child your generated object to an Empty GameObject (Make sure the generated GO is at 0,0,0 relative to the parent), and move the parent around. Sometimes this simplifies things, sometimes it doesn’t, but it’s worth a quick try.

  2. Calculate the “Center of mass” of the generated object. Here’s the gist: After it’s generated, get the mesh from the MeshFilter. Sum up all of the vectors in the mesh, divide by the number of vectors, to get an average position. (Note: If one side has a lot more triangles than another, the center will trend toward the side with more triangles). You can then try an offset by this position, or go through and subtract this position from all the vectors to re-center it a bit.

  3. Calculate the “render center” of the generated object. Here’s the gist: After it’s generated, get the mesh from the MeshFilter. Find the min and max x,y,z values for all vectors in the mesh. Take the max, subtract the min, then divide by two (Note, if the model has tall bits like a space station with antennas, this center will tend more toward those tall bits). You can then try an offset by this position, or go through and subtract this position from all the vectors to re-center it a bit.

Good luck!