Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

RectTransform.LookAt doing unexpected behavior.

Discussion in '2D' started by Sm0keh, Nov 30, 2017.

  1. Sm0keh

    Sm0keh

    Joined:
    May 30, 2012
    Posts:
    17
    Hello,

    I've recently been having some issues using the LookAt function on RectTransforms. Considering RectTransforms are for 2D/UI objects, I assumed the LookAt function should account for the fact that it is a 2D object.

    But when I try to make one RectTransform look at another point in 2D space, it is rotating my RectTransform only on the X and Y axis, when it should only be rotating it on the Z axis. This effect is distorting my UI image, am I not using this function the right way?

    Thanks for any help.
     
  2. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    RectTransform inherits from Transform, and LookAt is a function of Transform.
    https://docs.unity3d.com/ScriptReference/Transform.LookAt.html

    That function points the Z axis ("forward" axis).

    Here's a pretty commonly used mathematical method for doing a 2D LookAt:
    Code (CSharp):
    1. Vector3 relative = transform.InverseTransformPoint(target.position);
    2. float angle = Mathf.Atan2(relative.x, relative.y) * Mathf.Rad2Deg;
    3. transform.rotation = Quaternion.Euler(0, 0, -angle);
     
    ycanatilgan likes this.
  3. ycanatilgan

    ycanatilgan

    Joined:
    Aug 23, 2017
    Posts:
    30
    Helped me lot! Thanks!