I need to point the Z-axis of one vector toward another reference vector. I am having difficulty with some of the math.
Here is my code thus far:
Vector3 one = new Vector3(0.8, 3.49, 0.34); Vector3 two = new Vector3(0.9, 3.20, 0.17K);
I want to rotate z axis of one to point directly towards two. For that, I have to calculate the Direction.
Vector3 Direction = one - two;
Then I calculate the angle between the Direction vector and z axis of one.
// angle subtended by z axis of "One" and direction vector
var angleZ = D.Angle(new Vector3(0,0,one.z));
// angle subtended by y axis of "One" and direction vector
var angleY = D.Angle(new Vector3(0, one.y, 0));
// angle subtended by x axis of "One" and direction vector
var angleX = D.Angle(new Vector3(one.x, 0, 0));
I then applied a rotation of the z axis of vector one by the angle calculated earlier,
One.Rotate(Vector3.ZVector, angleZ);
but the rotation is not perfect.
I am sorry that i am not writing actual mathematics as i am using .net framework to write code but need some help in finding math.
It would be great help if someone could guide me about what i am doing wrong here.
I don't quite follow the method you used, and so I can't tell you what in there is incorrect. But I'll tell you how I would go about it.
If I understand you correctly, you want to rotate some source vector $\vec S$ so that its $z$-axis points in the same direction as some target vector $\vec T$. To figure out how to do this, we need to know the angle by which to rotate, and the axis of rotation (I am unfamiliar with .NET, but I assume it has---or someone on the internet has written---a function that can perform rotations given an angle and an axis vector). To compute the angle of rotation, we can use the dot product identity $$ \vec A \cdot \vec B = AB \cos \theta $$ where $A$ and $B$ (without the arrows on top) denote the magnitude of the vectors, i.e. $$ A = |\vec A| = \sqrt{A_x^2 + A_y^2 + A_z^2} $$ We can solve the first equation for $\theta$ to obtain $$ \theta = \cos^{-1} \left(\frac{\vec A \cdot \vec B}{AB} \right) $$ And as for a rotation axis, it must be orthogonal to both the $z$-axis and the target vector $\vec T$. We can find an orthogonal vector by taking the cross product of the $z$ unit vector $\hat k = (0,0,1)$ with the target vector $\vec T$.