Consider the following situation:
There are two GameObject
s :
_pivot
_objectToRotate
_pivot
is constantly performing some arbitrary rotation around itself.
How would I get _objectToRotate
to perform exactly “the same” rotation that _pivot
had performed but around _pivot
as opposed to around itself?
Essentially, _pivot
would act as a pivot for _objectToRotate
. But also their orientations should align. Say, if _pivot.transform.forward == _objectToRotate.transform.forward
before the rotation, then _pivot.transform.forward == _objectToRotate.transform.forward
after the rotation.
The following code solves this problem if _pivot
’s rotation is known:
// apply some rotation to _pivot
_pivot.transform.RotateAround(_pivot.transform.position, new Vector3(1, 1, 1), 90 * Time.deltaTime);
// apply the desired "pivoted" rotation to _objectToRotate
_objectToRotate.RotateAround(_pivot.transform.position, new Vector3(1, 1, 1), 90 * Time.deltaTime);
But how do I do this dynamically if I don’t know _pivot
’s rotation?
Storing _pivot
’s forward vector inside pivotForwardLastUpdate
, I came very close to solving this, using the following snippet:
// determine _pivot's rotation around the axes since last update
float xRotationSinceLastUpdate = Vector3.SignedAngle(_pivot.transform.forward, pivotForwardLastUpdate, Vector3.right);
float yRotationSinceLastUpdate = Vector3.SignedAngle(_pivot.transform.forward, pivotForwardLastUpdate, Vector3.up);
float zRotationSinceLastUpdate = Vector3.SignedAngle(_pivot.transform.forward, pivotForwardLastUpdate, Vector3.forward);
// apply _pivot's rotation since last update to _objectToRotate (around the axes)
_objectToRotate.RotateAround(_pivot.transform.position, Vector3.right, -xRotationSinceLastUpdate);
_objectToRotate.RotateAround(_pivot.transform.position, Vector3.up, -yRotationSinceLastUpdate);
_objectToRotate.RotateAround(_pivot.transform.position, Vector3.forward, -zRotationSinceLastUpdate);
This makes _objectToRotate
move along the correct trajectory with the correct orientation. But it moves along the trajectory faster than _pivot
for some reason.
I’ve been struggling with this all day - help is much appreciated!