- Home /
transform.LookAt(target); in 2D?
You probabaly knows what the line does in the title. It makes the attached object point at the "target" which is a variable. Well it works fine in 3d, but not in 2d. In 2D, the game is in layers, so if i want it to point at something which is some layers behind the "pointer" it rotates against it. But i only want it to point at the object in a 2d perspective, so it only rotates on the Z axis. How do i do that?
By the wat the "pointer" is a arrow that shows you were to go.
Answer by iqbalklv · Oct 19, 2018 at 12:19 PM
I think this is the best one.. insert the tag of the object that u want to look at and play with the offset
public string Tag;
public float offset;
private Transform target;
private Vector3 targetPos;
private Vector3 thisPos;
private float angle;
void Start ()
{
target = GameObject.FindGameObjectWithTag(Tag).GetComponent<Transform>();
}
void LateUpdate()
{
targetPos = target.position;
thisPos = transform.position;
targetPos.x = targetPos.x - thisPos.x;
targetPos.y = targetPos.y - thisPos.y;
angle = Mathf.Atan2(targetPos.y, targetPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle + offset));
}
the offset is used just in case your sprite doesn't look "up"
Answer by VesuvianPrime · May 16, 2014 at 08:44 AM
You can flatten your lookat position in the appropriate axis:
Vector3 targetPos = target.transform.position;
Vector3 targetPosFlattened = new Vector3(targetPos.x, targetPos.y, 0);
transform.LookAt(targetPosFlattened);
Answer by burnsky · Apr 12, 2021 at 11:17 AM
There's an amazingly simple solution in this thread (NOT the one marked as 'best' but the one below with the many votes!)
I save you a click:
transform.right = target.position - transform.position;
Just be sure target and transform are in the same Z, if not you may have to flat this coordinate.
Answer by BVGuled · Mar 09 at 04:32 AM
first you have to take the direction to target gameobject then use Quaternion.FromToRotation(Vector3.up, direction) : the first parameter is the current gameobject's up direction and second parameter is the direction to the target gameobject.
public Transform target;
private void Update()
{
Vector2 direction = target.position - transform.position;
transform.rotation = Quaternion.FromToRotation(Vector3.up, direction);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613145147im_/https://answers.unity.com/themes/thub/images/avi.jpg)