Rotating procedurally generated meshes
I am creating voxel-based game (Minecraft etc.) and I was wondering how to rotate chunk parts that are more complex than simple squares, like the sides of a cube are.
For example, I created a staircase by manually constructing the mesh from code by giving the script the x,y,z coordinates of the virtual cube the staircase should appear in.
Now, how must I change the vertex coordinates of the staircase mesh so it gets rotated 90 degrees? Keep in mind that I can't just rotate the whole gameobject because the stairs would be part of a chunk's mesh.
Part of the code (creates vertices for one side of a very simple two-step staircase):
List<Vector3> vertices = new List<Vector3>();
int x = 4;
int y = 0;
int z = 3;
int angle = 0;//0 = 0 degrees, 1 = 90, and so on.
vertices.Add(new Vector3(x, y, z));
vertices.Add(new Vector3(x, y + 1, z));
vertices.Add(new Vector3(x + 0.5f, y + 1, z));
vertices.Add(new Vector3(x + 0.5f, y + 0.5f, z));
vertices.Add(new Vector3(x + 1, y + 0.5f, z));
vertices.Add(new Vector3(x + 1, y, z));
Answer by robertbu · Aug 06, 2014 at 06:04 PM
Untested on my part, but I think you can just do:
center - Vector3 around which you want to rotate the submesh
v - a vertex to rotate
q - a Quaternion representing the rotation you want to do
v = q * (v - center) + center;
So cycle through the vertex positions in the submesh you want to rotate, and apply the above to each one.
You are, once again, my hero! It worked flawlessly, and it's far easier than my idea of somehow converting each vertex position while building the mesh :) A million thanks! Now I can fill my dungeon with all sorts of procedurally generated scenery without having to use hundres of gameObjects.
The center variable is, for my script, just (x + 0.5f, y, z + 0.5f).
Hello, this worked great for me aswell, but I was wondering If you could explain the maths behind it, I feel like I am cheating if i dont know how it works. Thanks!
public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles)
{
return Quaternion.Euler(angles) * (point - pivot) + pivot;
}
It's the code he explained.
Answer by BergOnTheJob · Jul 10, 2020 at 05:14 PM
If anyone is looking, this tool can rotate vertices of a mesh, and transform vertices using handle manipulation or directly entering the x,y,z coordinates of each vertex. https://assetstore.unity.com/packages/slug/166155
it also has a bunch of other tools to further model your staircase or any object's mesh.
Your answer
Follow this Question
Related Questions
Rotate LOCAL y axis to match Joystick input 0 Answers
Help with raycast for for wall detection 1 Answer
How do I find the rotation of a game object in relation to its grandparent 1 Answer
How to rotate the player towards a Vector2? 1 Answer
How do you rotate a rigidbody while maintaining world-coordinate velocity? 0 Answers