Quaternions: Setting rotation of one gameObject to Y,Z-Axis rotation of gameObject-A and Z-Axis position of gameObject-B
I'm trying to set the rotation of a gameObject so that it's X,Y,Z rotation is based on 2 seperate gameObjects:
The Y and Z-Axis rotation is based on Y and Z-axis rotation of one gameObject.
And its X-Axis rotation is based on the Z-Axis localPosition of another gameObject.
Any idea on how to go about doing this?
What I have so far:
Quaternion combinedQuaternion;
GameObject mainGameObject;
GameObject rotateAxisYZ;
GameObject moveAxisZ;
float xRotate, yRotate, zRotate;
void RotateMainObject()
{
// Setting x, y, z euler angle values of mainGameObject to rotateAxisYZ and moveAxisZ
xRotate = moveAxisZ.transform.localPosition.z * 20;
yRotate = rotateAxisYZ.transform.localEulerAngles.y;
zRotate = rotateAxisYZ.transform.localEulerAngles.z;
mainGameObject.transform.localEulerAngles = new Vector3(xRotate, yRotate, zRotate);
// Combining euler angles into Quaternion form and setting it to mainGameObject rotation
combinedQuaternion.eulerAngles = mainGameObject.transform.localEulerAngles;
mainGameObject.transform.rotation = combinedQuaternion;
}
This works well up to a point it seems. As long as the main gameObject is rotating on the X and Y axis alone - all's good. Once I introduce Z axis rotation - there's axis swapping and everything goes haywire. Anyone know of any possible solutions?
Ok, I've just solved the problem. Was working on it for days and managed to solve it a few $$anonymous$$utes after posting haha. It was a rather simple fix. Here it is below:
void Rotate$$anonymous$$ainObj()
{
Quaternion x = Quaternion.Euler(moveAxisZ.transform.localPosition.z * 100, 0, 0);
Quaternion y = Quaternion.Euler(0, rotateAxisYZ.transform.localEulerAngles.y, 0);
Quaternion z = Quaternion.Euler(0, 0, rotateAxisYZ.transform.localEulerAngles.z);
Quaternion result = y * z * x;
mainGameObject.transform.rotation = result;
}
You can multiply the relevant floats with your input floats if need be. It was interesting to see that if the resulting quaternion was not multiplied in the order of y*z*x then the axes still do go nuts. I guess that's just the nature of matrix multiplications. Too bad it's not that intuitive. So a bit of trial and error is needed, but a very good and easy fix!
Your answer
Follow this Question
Related Questions
Using Local Angles to target enemy object 0 Answers
Help with suns rotation 0 Answers
Quaternion.Euler doesn't work right? 2 Answers
Rotation Problem on X Axis over 90 and -90 degrees! 0 Answers