Aligning two game objects position/rotation

I have two empty game objects (with different parents) at different positions and with different rotations. I want to align them such that the second game object is placed in the same position as the first game object and with its z axis (i.e. the editor blue arrow) facing in the complete opposite direction to the first game objects z axis. The second game objects original z rotation should, however, be retained.

I tried doing this by:

  • Storing the second game objects local z rotation
  • Setting the second game objects position/rotation to the same as the
    first game object
  • Rotating the second game objects 180 degrees on the x axis so the “blue
    arrows” of the objects are facing in
    opposing directions
  • Finally I set the second game objects local z rotation back to it’s
    previous z rotation.

The problem is this doesn’t work as i’d expect, the rotations are often wrong. The only reason I can think of is because of the way euler angles work where you can have several different euler values for one quaternion (so resetting the second game objects local euler to its previous value won’t work).

Does anyone know how I might solve this problem with quaternions?

I did something very similar to this. I know this is a year late but I just started Unity and maybe this will be helpful to someone else. I was aligning my two objects on their blue axis in local mode. You can use the forward vector for this. If there’s some other axis you want to align on, use up or right vectors of the transform.

transformB.forward * -1);

This will give you how much A needs to rotate to align itself with B. You also need to set their transform.positions to be the same afterwards.

Did you try those ?

Try to use this:

var pos2Keep : float = 10; //the position (x or y or z) that u wanna keep for the object u're going to align
var obj1 : Transform; //object u're aligning the other one to
var obj2 : Transform; //object u align

function start () {
pos2Keep = obj2.position.x; //or y or z
obj2.position = Vector3(pos2Keep, obj1.postion.y, obj1.position.z);
obj2.rotation = Vector3(obj1.rotation.x, obj1.rotation.y, obj1.rotation.z);