Advertisement
KeithS

Cross Product Normalized Vector

Apr 8th, 2012
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. using namespace std;
  5.  
  6. struct vector
  7. {
  8.     float x;
  9.     float y;
  10.     float z;
  11. };
  12.  
  13. int main()
  14. {
  15.     vector vert[3];
  16.  
  17.     vert[0].x = 25.0f;
  18.     vert[0].y = 15.0f;
  19.     vert[0].z = 15.0f;
  20.  
  21.     vert[1].x = 50.0f;
  22.     vert[1].y = 20.0f;
  23.     vert[1].z = 20.0f;
  24.  
  25.     vert[2].x = 30.0f;
  26.     vert[2].y = 40.0f;
  27.     vert[2].z = 5.0f;
  28.  
  29.     // Get the vectors for each vertice...
  30.     vector vec1, vec2;
  31.  
  32.     vec1.x = vert[1].x - vert[0].x;
  33.     vec1.y = vert[1].y - vert[0].y;
  34.     vec1.z = vert[1].z - vert[0].z;
  35.  
  36.     vec2.x = vert[2].x - vert[0].x;
  37.     vec2.y = vert[2].y - vert[0].y;
  38.     vec2.z = vert[2].z - vert[0].z;
  39.  
  40.     // Get the cross product...
  41.     vector x_prod;
  42.  
  43.     x_prod.x = (vec1.y * vec2.z) - (vec1.z * vec2.y);
  44.     x_prod.y = -((vec1.x * vec2.z) - (vec1.z * vec2.x));
  45.     x_prod.z = (vec1.x * vec2.y) - (vec1.y * vec2.x);
  46.  
  47.     // Normalize the cross product...
  48.     vector norm;
  49.     float normal_total = sqrtf(powf(x_prod.x, 2) + powf(x_prod.y, 2) + powf(x_prod.z, 2));
  50.  
  51.     norm.x = x_prod.x / normal_total;
  52.     norm.y = x_prod.y / normal_total;
  53.     norm.z = x_prod.z / normal_total;
  54.  
  55.     cout << "Normal x (" << norm.x << "), y (" << norm.y << "), z (" << norm.z << ")" << endl;
  56.  
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement