Skip to content

Instantly share code, notes, and snippets.

@marcteys
Last active February 16, 2019 08:13
Show Gist options
  • Save marcteys/1f64eea68cdf9c1fcc20 to your computer and use it in GitHub Desktop.
Save marcteys/1f64eea68cdf9c1fcc20 to your computer and use it in GitHub Desktop.
Extension Method Unity
using UnityEngine;
using System.Collections;
public static class ExtensionMethods {
public static Vector3 GetScreenPosition(Transform transform, Canvas canvas, Camera cam)
{
Vector3 pos;
float width = canvas.GetComponent<RectTransform>().sizeDelta.x;
float height = canvas.GetComponent<RectTransform>().sizeDelta.y;
float x = Camera.main.WorldToScreenPoint(transform.position).x / Screen.width;
float y = Camera.main.WorldToScreenPoint(transform.position).y / Screen.height;
pos = new Vector3(width * x - width / 2, y * height - height / 2);
return pos;
}
public static float Map(this float value, float low1, float high1, float low2, float high2){
float val = low2 + (value - low1) * (high2 - low2) / (high1 - low1);
if (val > high2) {
val = high2;
}
return val;
}
public static bool RoughlyEqual(float a, float b)
{
float treshold = 0.02f; //how much roughly
return (Mathf.Abs(a - b) < treshold);
}
public static Vector3 RotatePointAroundPivot(this Vector3 point,Vector3 pivot, Vector3 angles) {
Vector3 dir = point - pivot; // get point direction relative to pivot
dir = Quaternion.Euler(angles) * dir; // rotate it
point = dir + pivot; // calculate rotated point
return point; // return it
}
// public static float Round (float value, int digits) {
// float mult = Mathf.pow(10.0f, (float)digits);
// return Mathf.Round(value * mult) / mult;
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment