Unfortunately there is no Transform.LookAt2D in Unity as for now in Unity5. BUT with an extension method this can be added into the API quick and easy!.
Its pretty simple. We just need to have a namespace included wherever we want to use Transform.LookAt2D and thats pretty much!, here’s how:
Lets create the extension method for LookAt2D:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using UnityEngine; namespace UnityTransformExtensions { public static class TransformExtension { //first arg is the class we want to add the extension method to. public static void LookAt2D(this Transform tr, Transform target) { Vector3 relative = tr.InverseTransformPoint(target.position); float angle = Mathf.Atan2(relative.x, relative.y) * Mathf.Rad2Deg; tr.Rotate(0,0, -angle, Space.Self); } public static void LookAt2D(this Transform tr, Vector3 pos) { Vector3 relative = tr.InverseTransformPoint(pos); float angle = Mathf.Atan2(relative.x, relative.y) * Mathf.Rad2Deg; tr.Rotate(0,0, -angle, Space.Self); } } } |
And then we just need to call it from any of our scripts as part of the Transform methods! here’s a quick example:
1 2 3 4 5 6 7 8 9 10 |
using UnityEngine; using System.Collections; using UnityTransformExtensions;//Remember to include the extension namespace public class LookAt2DTest : MonoBehaviour { void Update () { Vector3 lookPoint = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position); transform.LookAt2D(lookPoint);//called like its part of the API! } } |
Quick, easy and clean!