Biel Simon Biel Simon - 9 months ago 60
Java Question

Rotating a vector by angle and axis in java

I know there are lots of questions and answers about this topic or related but i've beenn trying for 2 hours and still haven't benn able to figure it.

I would like to get a function that looks like this:

public static Vector rotateVector(Vector v, Vector axis, double angle){


Where the axis is a unit vector that defines the plane of rotation (the vector v rotates towards the vector axis if angle is positive)

I have already taken a look at rotation matrices but haven't been able to implement those to the above function

Answer Source

Rotating (x, y, z) counter clockwise around unit vector (u, v, w) by angle theta produces a vector (xPrime, yPrime, zPrime):

double xPrime = u*(u*x + v*y + w*z)*(1d - Math.cos(theta)) 
                + x*Math.cos(theta)
                + (-w*y + v*z)*Math.sin(theta);
double yPrime = v*(u*x + v*y + w*z)*(1d - Math.cos(theta))
                + y*Math.cos(theta)
                + (w*x - u*z)*Math.sin(theta);
double zPrime = w*(u*x + v*y + w*z)*(1d - Math.cos(theta))
                + z*Math.cos(theta)
                + (-v*x + u*y)*Math.sin(theta);

Source here.