- Home /
Looking at a target in 2D
I watched the Live Training session about Top Down 2D Game Basics and there were 2 cases when you set your transform to look at a specific target via code. The first time you set the player look at the mouse position and the second time you set an enemy to look at the player, so I'd say the functionality is pretty similar. The code snippets where you set the rotation are the following:
Player looks at mouse position: Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); Quaternion rot = Quaternion.LookRotation(transform.position - mousePosition, Vector3.forward); transform.rotation = rot; transform.eulerAngles = new Vector3(0, 0, transform.eulerAngles.z);
Enemy looks at player position: float z = Mathf.Atan2((player.transform.position.y - transform.position.y), (player.transform.position.x - transform.position.x)) * Mathf.Rad2Deg - 90; transform.eulerAngles = new Vector3(0, 0, z);
What I don't get is why we can't use the first method in a similar way for the second case. I thought that, if I put player.transform.position instead of mousePosition, then I would get the desired result, but it doesn't work. Why? Here's what I tried more exactly:
Quaternion rot = Quaternion.LookRotation(transform.position - player.transform.position, Vector3.forward);
transform.rotation = rot;
transform.eulerAngles = new Vector3(0, 0, transform.eulerAngles.z);
I would advise you to just stick with the Atan2 solution. What they did is kind of weird, probably inefficient, and, if I understand it correctly, it's sensitive to the relative Z-values, which is why your version of it doesn't work.