I know there's a million questions on rotating, I've tried and read many things but I can't seem to solve this particular problem.
The only way I can think to explain it properly is with some poorly drawn diagrams so here goes!
I have a parent object, and a child object (here it's represented as a die where opposite faces add up to 7), the axes in this diagram are the parents X, Y, and Z directions
Starting point:
I want the child object to have two methods that I'll call RotateZ
and RotateX
. RotateZ
and RotateX
should rotate the child dice around the parents Z and X axes in 90 degree steps.
RotateX:
RotateZ:
The code I currently have is this
void RotateZ(int value) {
transform.rotation *= Quaternion.AngleAxis(90f * value, pivot.transform.forward);
}
void RotateX(int value) {
transform.rotation *= Quaternion.AngleAxis(90f * value, pivot.transform.right);
}
I should note pivot is the parent object
This appears to work great if the child starts at (0, 0, 0)
rotation, repeatedly calling RotateZ
or RotateX
with (0, 0, 0)
starting point works great. This problem comes if for example I call RotateX
then RotateZ
.
After the initial RotateX
call it will look like this, giving the child a rotation of (90, 0, 0)
.
Then after a RotateZ
the desired result is this:
But instead I end up with this:
I'm really at a loss as to what I'm doing wrong. I have a feeling I've hit the limit of what I can do with Euler angles and I need to learn quaternions to prevent this problem. What rotation function do I need to get the desired result?