Search Unity

Quaternion.LookRotation Issue, need help!

Discussion in 'Scripting' started by soapstar, Jun 8, 2011.

  1. soapstar

    soapstar

    Joined:
    Apr 4, 2011
    Posts:
    56
    Currently i have a 'A frame' which rotates in and out, attached in between this a-frame (parent) is another object (child) which i want to hang freely as i rotate the a-frame back and forth.

    To do this I am using the Quaternion.LookRotation function on the 'hanging object' to make sure it is always looking down as i rotate the frame, this works perfectly. However when my hanging object gets to a certain Z rotation it then flips the hanging object around 180 degrees! I believe this is because it is trying to find the shortest rotation or something?

    Here is the code i currently have attached to my 'hanging object':

    Code (csharp):
    1. void Update() {
    2.  
    3.         transform.rotation = Quaternion.LookRotation(-Vector3.up, transform.parent.forward);
    4.  }

    Is there anyway i could stop this from happening? Or even any other method to allow me to do this?

    Any help would be HUGELY appreciated, this is very important that this works! :D
     
  2. Antitheory

    Antitheory

    Joined:
    Nov 14, 2010
    Posts:
    549
    Quaternion.LookRotation

    static function LookRotation (forward : Vector3, upwards : Vector3 = Vector3.up) : Quaternion

    Description

    Creates a rotation that looks along forward with the head upwards along upwards


    LookRotation is not what you want here.

    Do you want the object to keep the same exact same rotation as its parent rotates? Or do you want it to always look down but have it's "up" axis in-line with the "forward" axis of its parent?
     
  3. soapstar

    soapstar

    Joined:
    Apr 4, 2011
    Posts:
    56
    hey

    Yes i basically want to the child object to point down (world space Y axis) no matter what its parents rotation is?

    Ive also noticed using the LookAt function on two objects to point at each other they also flip round when there parent gets to a certain rotation!?

    Thanks
     
  4. Antitheory

    Antitheory

    Joined:
    Nov 14, 2010
    Posts:
    549
    Well then you can just get your childs rotation Quaternion before the parents starts rotating, and apply this value every frame:

    Code (csharp):
    1.  
    2. private Quaternion initialRotation;
    3.  
    4. void Start() {
    5.     initialRotation = transform.rotation;
    6. }
    7. void Update() {
    8.     transform.rotation = initialRotation;
    9. }
    10.  
    of course this will mean that the child will never deviate from its starting orientation... it can still move as usual. If you want you could also do this instead

    Code (csharp):
    1.  
    2. void Update() {
    3.     transform.localRotation= transform.parent.localRotation.Inverse;
    4. }
    5.  
    ..which is sort of self-explanatory.
     
unityunity