Go to notes and algorithms index. ~ Go to home page.

Rotate a vector.


Floating point version. Not tested.

The function does a rotation about the specified axis by p_radians. Specify the required axis p_axis as a capital X, y or Z in single quotes.

This is similar to the function rotate_2D_with_sine_and_cosine() -- see that function for explaination.

This function differs from rotate_2D_with_sine_and_cosine() in that is does the sine and cosine function calls itself rather than having those values passed-in as parameters.

You may have to adapt the calculations to suit your coordinate system -- to make rotations around certain axes clockwise or anticlockwise as appropriate.




typedef struct 
   {
   float x;
   float y;
   float z;
   } vector_3D;



void rotate_vector( vector_3D *p_vector_ptr, char p_axis, float p_radians )
   {
   //
   double x, y, z;
   

   switch( p_axis )
      {
      case 'X':
         z = (double) p_vector_ptr->y;
         z *= sin( (double) p_radians );
         z += ( (double) p_vector_ptr->z ) * cos( (double) p_radians );
   
         y = (double) p_vector_ptr->y;
         y *= cos( (double) p_radians );
         y += ( (double) p_vector_ptr->z  ) * sin( (double) p_radians );

         p_vector_ptr->y = (float) y;
         p_vector_ptr->z = (float) z;
         break;

      case 'Y':
         x = (double) p_vector_ptr->z;
         x = 0.0 - x;
         x *= sin( (double) p_radians );
         x += ( (double) p_vector_ptr->x ) * cos( (double) p_radians );
   
         z = (double) p_vector_ptr->z;
         z *= cos( (double) p_radians );
         z += ( (double) p_vector_ptr->x  ) * sin( (double) p_radians );

         p_vector_ptr->z = (float) z;
         p_vector_ptr->x = (float) x;
         break;

      case 'Z':
         x = (double) p_vector_ptr->y;
         x *= sin( (double) p_radians );
         x += ( (double) p_vector_ptr->x ) * cos( (double) p_radians );
   
         y = (double) p_vector_ptr->y;
         y *= cos( (double) p_radians );
         y += ( (double) p_vector_ptr->x  ) * sin( (double) p_radians );

         p_vector_ptr->y = (float) y;
         p_vector_ptr->x = (float) x;
         break;

      #if DIAGS
         default:
            err( 4597 );
      #endif
      }
   
   }