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

Rotation question.

Discussion in 'Scripting' started by Mastereve, Apr 7, 2009.

  1. Mastereve

    Mastereve

    Joined:
    Aug 16, 2008
    Posts:
    37
    Hello! I don't seem to figure out how to rotate an object so that it faces another object. If anyone can help me please, I already tried Quaternion.FromToRoation but didn't worked.

    Thnx!
     
  2. Scrat

    Scrat

    Joined:
    Apr 20, 2008
    Posts:
    316
    Transform.LookAt
     
  3. Mastereve

    Mastereve

    Joined:
    Aug 16, 2008
    Posts:
    37
    Thnx for the quick reply but I've tried that but i can't seem to make it work...

    Code (csharp):
    1.  
    2. var target: Transform;
    3. private var isClicked: boolean = false;
    4.  
    5. function Start();
    6. {
    7. target = transform.Find("target");
    8. }
    9. function FixedUpdate (){
    10.  
    11. if(isClicked)
    12. {
    13.      transform.LookAt(target);
    14. }
    15. }
    16. function OnGui()
    17. {
    18.     if(GUI.Button(Rect(0,0,60,50)"Face target");
    19.      {
    20.         isClicked = true;
    21.      }
    22.    else
    23.      {  
    24.         isClicked = false;
    25.      }
    26. }
    27.  
    This is a sample of what i am trying to make but it doesn't work. I also want to make the rotation smooth as if the object is aligning with the target.
     
  4. jonas-echterhoff

    jonas-echterhoff

    Unity Technologies

    Joined:
    Aug 18, 2005
    Posts:
    1,666
    Try this instead. OnGUI() gets called multiple times, so isClicked may be reset to false. As a general rule, when debuggig problems, always make sure your code is actually being called (just add a Debug.Log()).

    Code (csharp):
    1.  
    2. var target: Transform;
    3. private var isClicked: boolean = false;
    4.  
    5. function Start();
    6. {
    7. target = transform.Find("target");
    8. }
    9. function FixedUpdate (){
    10.  
    11. if(isClicked)
    12. {
    13.      transform.LookAt(target);
    14.         isClicked = false;
    15. }
    16. }
    17. function OnGui()
    18. {
    19.     if(GUI.Button(Rect(0,0,60,50)"Face target");
    20.      {
    21.         isClicked = true;
    22.      }
    23. }
    24.  
     
  5. Mastereve

    Mastereve

    Joined:
    Aug 16, 2008
    Posts:
    37
    Thnx a lot, it worked :D. Also if I'm not to greedy how can i make this rotation smooth as if the object is aligning? transform.LookAt is to straight forward...