Tag Archives: 2D

Unity realizes lookat in 2D

Since transform. Lookat makes z-axis look at the target, 2D is basically composed of x-axis and y-axis. So in 2D games, it’s not easy to use

So use code to implement a 2D lookat function

Example:

We keep the monster’s eyes on the cloud

The orientation of the monster’s eyes is the same as that of the localx axis, so make the monster look at the cloud and point the localx to the cloud

Script the monster

Scripting

Writing method 1:

	void Update () {
        Vector2 direction = target.transform.position - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
	}

Writing method 2:

void Update () 
    {
        Vector3 v = (target.position - transform.position).normalized;
        transform.right = v;
	}

Then move the cloud and the monster will follow