Hi All, I try to rotate an object which is in the center of a cube toward the cube’s vertices using a virtual reality controller (if that object’s forward direction is ‘almost towards’ to the vertex). I’ve tried:
Quaternion lookRotation = Quaternion.LookRotation(dirTo);
gameObject.transform.rotation = lookRotation;
and I’ve tried multiply with a defined rotation uses
Quaternion fromToRotation = Quaternion.FromToRotation( gameObject.transform.forward, dirTo);
gameObject.transform.rotation *= fromToRotation;
but both have the problem: when I rotate the object toward ‘global y (up)’ from the original direction, it rotates an additional 90 degree around the y-axle (in all other cases it works well).
What is wrong with my solution or is there a simple method to avoid this behavior, or what is the best practice for this kind of problem? Thanks in advance!
Well your issue is that Quaternion.LookRotation does not take one argument but two. However the second argument is optional and when not manually provided it defaults to Vector3.up
. This upvector is used as a “hint” how the rotation should be rotated around your provided forward vector. In most cases using just Vector3.up gives a reasonable result. However if your forward axis points along the up vector (up or down) the orientation around that axis can not be determined.
Your approach with FromToRotation should work. However it seems a bit strange that you rotate the current “gameobject” but you use the forward direction of that “m_controlledObject”. Are the two objects related in any way?
Note that free rotation in 3d space can result to some odd results. Rotating around an arbitrary axis could change the orientation completely so you might end up with a slight roll around z as well. In many cases we want to keep the orientation somewhat parallel to the ground. Think of a usual FPS / camera setup. You can rotate 360° around y but only ±90 on the local x axis. The z rotation usually stays 0.
Quaternions can perform any arbitrary rotation in 3d space. If you just calculate the rotation between two directions you get a rotation that rotates from that direction directly to the other direction. The axis of rotation will be perpendicular to the plane the two vectors lie in. This is essentially what FromToRotation does.