# Rotating Object to new position

Hey,

I try to rotate an object (a cylinder) that starts at point 1 [x1,y1,z1] and ends at point 2 [x2,y2,z2] in such way that point 1 is transformed to a known destination point [x_d1,y_d1,z_d1] and point 2 is transformed to a different known destination point [x_d2,y_d2,z_d2]. Source and destination point may in some cases be the same so the object should be able to rotate around its end point. I already tried to calculate rotation axis and angle based on a post from two years ago but couldn’t get it running for me.

Felix

Hey,

I tried many different ways but always get the same result. Here is some further info on my problem.

The two points are determined by spheres that can move. So the goal is to keep the cylinder between the two spheres, no matter how they move (actually there are limits).

I calculated the rotation axis by the cross product of the two vectors that go from one sphere to the other, one in previous state, one after transformation. The axis looks good so far.
The angle is calculated by the dot product of these two vectors. There seems to be some error, because the cylinder rotates not enough and for some reason translates towards the moving sphere. I translate the cylinder to the origin and back to rotate it around its center but that does not work. It is not rotating around the point I want it to rotate around, even with the back and forth translation. Does the calculcated axis have something to do with rotation center?

I have no idea where the error is and what causes it.

I hope someone can spot a mistake.

Regards,
Felix

First, you can use the magnitude of the cross product to determine the angle. This may be preferable to the dot product: you’re already calculating the cross product to find the axis, it’s more accurate for small angles, and it gets the sign correct. The dot product gives you cos(a), but cos(a)=cos(-a) so you can’t determine the direction of rotation. Either way, sin(a)=x and cos(a)=x both have two solutions in the range [-π,π]. Using both the dot product and cross product will give you a unique solution.

Given source points S1, S2 and destination points D1, D2, you can use e.g.:

``````
S=normalize(S2-S1);
D=normalize(D2-D1);
A=cross(S,D);
angle=atan2(length(A),dot(S,D))*180/M_PI;
glTranslate(-S1.x, -S1.y, -S1.z);
glRotate(angle, A.x, A.y, A.z);
glTranslate(D1.x, D1.y, D1.z);

``````

Unfortunately I have still the same problem. The cylinder rotates not enough and ends up over the sphere. Also the other end of the cylinder has moved out of its sphere towards the other sphere. Very strange behaviour.

UPDATE: It works now, the mistake was in the code delivering the coordinates of the two spheres. Thank you very much for your help! Best Regards,
Felix