Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to copy the direction which object is facing to another object?

Discussion in 'Scripting' started by FellowPlayer123, Oct 13, 2018.

  1. FellowPlayer123

    FellowPlayer123

    Joined:
    Dec 23, 2016
    Posts:
    114
    I have 2 objects: object A and object B.

    The object A is moving on the plane according to analog stick controller and it rotates around its own axis.

    I would like to copy the direction which the object A is facing to the object B.

    My current solution doesn't work.

    I copied transform.forward of the object A to transform.forward to the object B.

    The thing is it doesn't rotates on its own axis but with a wrong oring pivot point (look at the image I included).
     

    Attached Files:

  2. hpjohn

    hpjohn

    Joined:
    Aug 14, 2012
    Posts:
    2,190
    Copy the whole transform.rotation
    If they have a rotational offset from each other, then store that at start and apply the offset to the new rotation, something like:
    Code (CSharp):
    1. Quaternion offset = Quaternion.FromToRotation(a.rotation, b.rotation);
    2. ....
    3. b.rotation = offset * a.rotation;
    (guessed code without testing)
     
  3. FellowPlayer123

    FellowPlayer123

    Joined:
    Dec 23, 2016
    Posts:
    114
    Thank you very much for the reply but this solution doesn't work. I think it needs to be tuned up a little bit.
     
  4. FellowPlayer123

    FellowPlayer123

    Joined:
    Dec 23, 2016
    Posts:
    114
    Its funny because for the other object this code works perfectly fine:
    Code (CSharp):
    1. gameobjectA.transform.forward = gameobjectB.transform.forward;
    But in my case, the object B rotates not around its own axis but rather some strange axis as it is shown in the attachment image (first post).

    Any ideas why is it so and how to fix it?
     
  5. FellowPlayer123

    FellowPlayer123

    Joined:
    Dec 23, 2016
    Posts:
    114
    I solved it by parenting this object to the newly created empty object and rotating around its empty object.
     
  6. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    If you want to instantly be facing the same direction

    Code (csharp):
    1. object1.transform.rotation = object2.transform.rotation;