Search code examples
javavecmath

Rotations from javax.vectmath.matrix3d


After a long time, I try to use JAVA again. I'm using the vectmath package, with which I'd like to rotate a 3d vector with a rotation matrix. So I wrote that:

   double x=2, y=0.12;
   Matrix3d rotMat = new Matrix3d(1,0,0, 0,1,0, 0,0,1); //identity matrix
   rotMat.rotX(x); //rotation on X axis
   rotMat.rotY(y); // rotation on Y axis
   System.out.println("rot :\n" + rotMat); // diagonal shouldn't have 1 value on it

result:

rot :
0.9928086358538663, 0.0, 0.11971220728891936
0.0, 1.0, 0.0
-0.11971220728891936, 0.0, 0.9928086358538663

Unfortunately, it doesn't give me what I expected. It is like he ignored the first rotation (around X) and only take the second one (around Y). If I comment the rotMat.rotX(x); it gives me the same result.

I suspect either a mistake with the print, or with variable management.

Thanks


Solution

  • Methods rotX and rotY set/overwrite the matrix elements, so your subsequent call to rotY(y) cancels the call to rotX(x). Something like this should work:

    Vector3d vector = ... //a vector to be transformed
    double x=2, y=0.12;
    Matrix3d rotMat = new Matrix3d(1,0,0, 0,1,0, 0,0,1); //identity matrix
    rotMat.rotX(x); //rotation on X axis
    rotMat.transform(vector);
    rotMat.rotY(y); // rotation on Y axis
    rotMat.transform(vector);
    // the vector should now have both x and y rotation
    // transformations applied
    System.out.println("Rotated vector :\n" + vector);