Monday 5 November 2012

3D Math: Rotate to point

1. Problem description:

    We have :
              - 3d object that is (let's assume), centered on the Y axis
Cone was rotated to face the point (x1,y1,z1)



         - arbitrary point in space v1 with the coordinates (x1,y1,z1)

    We want :
        - obtain the rotation matrix or Quaternion that will rotate your object towards the arbitrary point (look at)
        - so, input parameter is v1 and output will be a 4x4 transformation matrix

    Optional :
        - other implementations to this issue will also take as input parameters a up vector (in this case is the OY axis) and a rotation center (i used (0,0,0))

2. Implementation :


         - we solve this by finding the axis-angle representation for the rotation
         - i see this as the most simplest way, as many frameworks will already have implementations for the all math required (Vector Normalization, Cross Product, Dot Product, Axis-Angle to Matrix conversion)
         - code example, using the Vector3, Matrix4 and Quaternion classes from LibGdx  :
vec.nor();  
float angle = (float) (180f / Math.PI * Math.acos(vec.dot(Yaxis)));

  vec.crs(Yaxis);

  if (vec.len() == 0) {
   vec.set(Zaxis);
  }
  quaterion.set(vec, angle);
  vec.crs(Yaxis);
  if (vec.len() == 0) {   vec.set(Zaxis);  }  quaterion.set(vec, angle);  transformMatrix.rotate(quaterion.conjugate());
             1. Normalize v1
             2  Find the angle between OY and v1 :
                        - calculate the dot product between the 2 vectors to get the cosine of the angle between them
                        - get the angle value in radians by applying arccosine
                        - convert to degrees if necessary
             3. Calculate cross product between the vectors, to obtain the rotation axis, the vector that is perpendicular on both OY and v1
             4. If the cross product is zero (vectors are parallel), we use OZ as rotation axis
             5. We now have a rotation axis and a rotation angle.
                 This can be used as input to create a transformation matrix or a Quaternion(indirect aproach).
                 If,  using something like the code above, make sure your roation matrix is set to identity
                 If, for some reason you need to do the math yourself, see Conversion_from_and_to_axis-angle

No comments:

Post a Comment