Search code examples
javavectorlwjgl

Trying to rotate 3D vector in java


Im trying to find the components/head of a 3D vector with in java. I have a already got the x,y,z variables setup and the corresponding rotation variables. Using these variables and vector math, I want to find the components after they have been rotated. You can think the x,y,z variables as a vector being translated.

Using the math from this post: Rotating a Vector in 3D Space

I wrote some code that was supposed to calculate position based on that last post:

//Rotate Z
x = (( x * Math.cos(radz)) - (y * Math.sin(radz)));
y = (( x * Math.sin(radz)) + (y * Math.cos(radz)));
//Ignore Z ###############################################

//Rotate Y
x = (( x * Math.cos(rady)) - (z * Math.sin(rady)));
//Ignore Y ###############################################
z = (( x * Math.sin(rady)) + (z * Math.cos(rady)));

//Rotate X 
//Ignore X ###############################################
y = (( y * Math.cos(radx)) - (z * Math.sin(radx)));
z = (( y * Math.sin(radx)) + (z * Math.cos(radx)));

Where x, y and z are the positions that need to be changed and radx, rady and radz are the degrees of rotation in radians.

Using this code, if you set the variables like so:

double radx = Math.toRadians(0f);
double rady = Math.toRadians(90f);
double radz = Math.toRadians(0f);

double x = 1;
double y = 0;
double z = 0;

System.out.println(x + " " + y + " " + z);

It outputs: 6.123233995736766E-17 0.0 6.123233995736766E-17

Which im fairly sure isn't accurate. . .

What am I doing wrong with this code? Is there a easier way to find the head of a 3D vector java?

Also I do have the joml library, but it seems to have the same issue with the vec.rotateX method.


Solution

  • You are updating your variables early. Try to:

    //Rotate Z
    double newX = (( x * Math.cos(radz)) - (y * Math.sin(radz)));
    y = (( x * Math.sin(radz)) + (y * Math.cos(radz)));
    //Ignore Z ###############################################
    
    x = newX;
    
    //Rotate Y
    newX = (( x * Math.cos(rady)) + (z * Math.sin(rady)));
    //Ignore Y ###############################################
    z = (( x * -Math.sin(rady)) + (z * Math.cos(rady)));
    
    x = newX;
    
    //Rotate X 
    //Ignore X ###############################################
    double newY = (( y * Math.cos(radx)) - (z * Math.sin(radx)));
    z = (( y * Math.sin(radx)) + (z * Math.cos(radx)));
    
    y = newY;