Created
July 31, 2017 16:20
-
-
Save hasanbayatme/0030c7aa307d26497c5b5f3397d8172e to your computer and use it in GitHub Desktop.
Useful Unity (Game Engine) Transform Extensions, LookAt2D (Make the 2D object look at specified position), ...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
/// <summary> | |
/// Transform extensions. | |
/// Useful transform utilities and methods. | |
/// </summary> | |
public static class TransformExtensions | |
{ | |
/// <summary> | |
/// Rotates the transform so the forward vector points at target's current position. | |
/// </summary> | |
/// <param name="transform">Transform.</param> | |
/// <param name="target">Target.</param> | |
public static void LookAt2D ( this Transform transform, Transform target ) | |
{ | |
transform.LookAt2D ( ( Vector2 )target.position ); | |
} | |
/// <summary> | |
/// Rotates the transform so the forward vector points at worldPosition. | |
/// </summary> | |
/// <param name="transform">Transform.</param> | |
/// <param name="worldPosition">World position.</param> | |
public static void LookAt2D ( this Transform transform, Vector3 worldPosition ) | |
{ | |
transform.LookAt2D ( ( Vector2 )worldPosition ); | |
} | |
/// <summary> | |
/// Rotates the transform so the forward vector points at worldPosition. | |
/// </summary> | |
/// <param name="transform">Transform.</param> | |
/// <param name="worldPosition">World position.</param> | |
public static void LookAt2D ( this Transform transform, Vector2 worldPosition ) | |
{ | |
Vector2 distance = worldPosition - ( Vector2 )transform.position; | |
transform.eulerAngles = new Vector3 ( | |
transform.eulerAngles.x, | |
transform.eulerAngles.y, | |
Mathf.Atan2 ( distance.y, distance.x ) * Mathf.Rad2Deg ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment