- Home /
How can I align axis with quaternion.fromToRotation?
Hey folks, going somewhat crazy here. Trying to align two transforms, so that a prefab can be instantiated and made to stand at a particular parent empty, standing upwards along a particular axis of the parent empty.
In the following image, I have a basic tree whose Y axis should aligned to the parent transform's -Z (minus z) axis.
I desire that the tree should be standing with the trunk in line with the blue axis of the parent transform, but 'growing' in the opposite direction to the blue arrow (the green ball of the 'tree' should be away from the transform's origin in the opposite direction to the blue arrow).
When the tree is instantiated, it is assigned the rotation of its parent transform and all axis of both objects are aligned.
I identify the rotation between the axis and apply it to the tree's transform, following the example on this page. While that code works on a simple test project, I can't get it to work in my work scene. At the moment, my code reads as follows:
tempTree.rotation = Quaternion.FromToRotation(tempTree.up, -treeArray[i].transform.forward);
I have also attempted using the code so that the rotation from Quaternion.FromToRotation is applied to the transform.rotation through multiplication.
tempTree.rotation *= Quaternion.FromToRotation(tempTree.up, -treeArray[i].transform.forward);
In both cases, my result is as seen in the attached image - the tree is rotated to a seemingly arbitrary angle, entirely unsuitable for the project.
Please, if you can, help me out with this one. Time is short, and I'm going out of my tree. =D
Answer by Reverend-Speed · Sep 18, 2019 at 09:21 AM
It turns out that the correct code is...
tempTree.rotation = Quaternion.FromToRotation(Vector3.up, -treeArray[i].transform.forward);
This is basically, exactly like the example code from the documentation. I had been under the impression that I was supposed to take the tree's rotation and turn it towards the target rotation, but apparently not so... To quote Antistone on the Unity forums,
You are setting the tree's rotation in world space, so you want the rotation that would move world up to point in a certain direction, not the tree's current up (which you are overwriting).
I'm honestly still a bit confused about this, but you can't argue with results...!