Search Unity

Locking the x and z axis while using transform.LookAt()?

Discussion in 'Scripting' started by MSachs, Mar 14, 2018.

Thread Status:
Not open for further replies.
  1. MSachs

    MSachs

    Joined:
    Nov 22, 2017
    Posts:
    122
    Hi

    I have an Object which I would like to look at the camera and all times I wanted to use transform.LookAt() but it uses all axis and I couldn't find a way to lock the x and z axis so it stays flat on the ground. I feel like the other posts in this forum regarding this topic aren't working anymore (outdated?)

    Hope there is a way to do this :)

    Thanks
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Code (csharp):
    1.  
    2. Vector3 rotation = Quaternion.LookRotation(target).eulerAngles;
    3. rotation.y = 0f;
    4.  
    5. transform.rotation = Quaternion.Euler(rotation);
    6.  
     
    Xsodiaz and MSachs like this.
  3. StickyHoneybuns

    StickyHoneybuns

    Joined:
    Jan 16, 2018
    Posts:
    207
    Isn't this opposite of what he wants?

    Shouldn't it be this:

    Code (csharp):
    1.  
    2. Vector3 rotation = Quaternion.LookRotation(target).eulerAngles;
    3. rotation.x = 0f;
    4. rotation.z = 0f;
    5.  
    6. transform.rotation = Quaternion.Euler(rotation);
    7.  
     
    MSachs and GroZZleR like this.
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I honestly don't think an answer to this would be outdated. :)

    3 that are working..
    Code (csharp):
    1. Vector3 rot = Quaternion.LookRotation(target.position - transform.position).eulerAngles;
    2. rot.x = rot.z = 0;
    3. transform.rotation = Quaternion.Euler(rot);
    4.  // or
    5. Vector3 newtarget = target.position;
    6. newtarget.y = transform.position.y;
    7. transform.LookAt(newtarget);
    8. // or
    9. Vector3 dir = target.position - transform.position;
    10. dir.y = 0;
    11. transform.rotation = Quaternion.LookRotation(dir);
     
    maramak, SKizil, elsharkawey and 8 others like this.
  5. MSachs

    MSachs

    Joined:
    Nov 22, 2017
    Posts:
    122
    Thanks guys! :)

    Actually found a video tutorial on youtube which works. Thanks again!

     
    qwetito and Usaneers_Member_1 like this.
  6. Nichathan

    Nichathan

    Joined:
    Mar 8, 2020
    Posts:
    23
    Why would anyone be daft enough to post a video in a forum? Those expire and get banned depending on your region. If you have working code please post it as either that video has expired or it is not available in my country.
     
Thread Status:
Not open for further replies.