Using quaternions to align game objects.

Hi, I have a script that I use to align game objects to each other, and it’s worked pretty well up until now, but I’ve recently ran into a problem that I’m not entirely sure how to fix. Let me explain.

The script looks something like this

class Aligner : MonoBehaviour{
    Vector3 Orientation; //Vector relative to the game object
    Vector3 WorldOrientation { get { return transform.localToWorldMatrix * Orientation.normalized; } } //Orientation in world space

    public void AlignTo(Aligner aligner) {

      Vector3 axis = Vector3.Cross(aligner.WorldOrientation, Orientation); 
      float angle = Vector3.Angle(aligner.WorldOrientation, -Orientation);

      axis = axis == Vector3.zero ? Vector3.forward : axis; //If the two orientations are the same, Vector3.cross returns Vector.zero, which isn't an axis

      transform.rotation = Quaternion.AngleAxis(angle, axis);
    }
  }

The function AlignTo rotates the game object so that the Orientation Vector points in the opposite direction of the aligner that gets passed to it.

This works fine with translation, the problem comes when I begin to rotate the game object, and realign game objects to it.

Basically, I when I move a game object(Which I’ll call the parent), and update the position of other game objects(Which I’ll call children) to follow it, I want it to essentially work as if the children were children of the parent in the hierarchy.

I understand this is because I’m storing my Orientation as a Vector3, and to fix this I just need to use a quaternion, but I can’t figure out how to get this effect to work with quaterions, can anyone help me?

Excuse me if my explanation is bad. I’m quite bad at explaining

you could use Quaternion.FromToRotation to get the difference in rotation from the aligner to the alignee. turn, every time the aligner rotates, multiply it’s rotation by the saved and apply it to the alignee.