Lorry Laurence mcLarry
Lorry Laurence mcLarry

Reputation: 394

Unity/C# - Existing API for applying 3D rotations?

I want to proceduraly generate meshes. I created a method to supply the vertices of a circle. The idea is that it creates a shape in 2d and then rotates it in 3d assuming that "rotation" is the vector of the shapes normal axis.

 public List<Vector3> Loop (Vector3 center, Vector3 rotation, float radius, int divisions)
 {
     List<Vector3> loop = new List<Vector3>();
     for(int p = 0; p < divisions; p++)
     {
         float u = (float)Math.Cos(2 * Math.PI * p / divisions) * radius;
         float v = (float)Math.Sin(2 * Math.PI * p / divisions) * radius;
         float x = 0;
         float y = 0;
         float z = 0;
         // Apply rotation to u & v to get x, y, z
         loop.Add(new Vector3(x, y, z));
     }
     return loop;
 }

Creating the circle in 2d (u & v) was super easy but when I looked into applying 3d rotations, it seemed to be a complete rabbit hole completely beyond my comprehension.

Is there a way to use existing API to do this?

Upvotes: 1

Views: 56

Answers (1)

Ruzihm
Ruzihm

Reputation: 20259

I would pass in an axis parameter that you are rotating rotation around, then use Cross products to find the "up" direction for the "forward" that is the normal of the circle.

Use Quaternion.LookRotation, then Quaternion * Vector3 to apply the rotation to the position:

public List<Vector3> Loop (Vector3 center, Vector3 rotation, Vector3 axis, float radius, int divisions)
 {
     List<Vector3> loop = new List<Vector3>();
     for(int p = 0; p < divisions; p++)
     {
         float u = (float)Math.Cos(2 * Math.PI * p / divisions) * radius;
         float v = (float)Math.Sin(2 * Math.PI * p / divisions) * radius;
         Vector3 fromPosition = new Vector3(u, v, 0f);

         Vector3 up = Vector3.Cross(rotation.normalized, axis.normalized);

         Quaternion rot = Quaternion.LookRotation(rotation, up);
         loop.Add(rot * fromPosition);
     }
     return loop;
 }

So you could do something like: List<Vector3> res = Loop(Vector3.zero, Vector3.up, Vector3.right, 10f, 20);

Upvotes: 1

Related Questions