The functionality I am trying to implement, consists of rotating one Transform and appling this rotation to other relevant Transforms in the scene. To make it a bit more clear: I have several objects in the scene. When I grab one (lets call it parent) and rotate it, the others (children) should rotate relative of their own position and rotation to the grabbed object around this grabbed object.
It is exactly the same what parenting does with its child objects when rotating the parent. Unfortunatly I cant just change the hierachy so I am bound to have different objects on the same hierachy level.
So far I have managed to rotate the children relative to the parent but when I grab the parent object the child objects first reorient themselves. After reorienting they do the right thing and rotate and move relative to the parent.
Here are two objects. The left one should rotate relative to the right one.
As the right one is grabbed and the procedure starts, the child object first jumps to another position with another rotation
I feel kind of stupid not seeing where this behaviour comes from. I use a coroutine to be able to construct the functionality in another script. As long as the coroutine is running, the child object should be moved and rotated relatively.
I first calculate the needed offsets of the position and rotation at startup:
Vector3 offsetPos = child.position - parent.position;
Quaternion offsetRot = child.rotation * Quaternion.Inverse(parent.rotation);
Then I apply the calculations in a loop:
while (true)
{
child.position = parent.rotation * offsetPos + parent.position;
child.rotation = parent.rotation * offsetRot;
yield return new WaitForFixedUpdate();
}
The loop runs as long as the parent object is grabbed and should place and orient the child accordingly.
I assume that my fault is located somewhere around calculating the offsets as once grabbed and reoriented, the children move and rotate exactly as they should.
If somebody has an idea where my mistake could hide I would be really happy if you could tell me.
Here is the related function as a whole:
public override IEnumerator TransformGroupMember(Transform child, Transform parent)
{
//calculate offsets
Vector3 offsetPos = child.position - parent.position;
Quaternion offsetRot = child.rotation * Quaternion.Inverse(parent.rotation);
//apply the relative transformation as long as the coroutine is running
while (true)
{
child.position = parent.rotation * offsetPos + parent.position;
child.rotation = parent.rotation * offsetRot;
yield return new WaitForFixedUpdate();
}
}
Since this is my first question asked, I also welcome any suggestions about tips and tricks or changes.