Skip to content

Instantly share code, notes, and snippets.

@AdamCarballo
Created February 11, 2017 11:50
Show Gist options
  • Select an option

  • Save AdamCarballo/5fd4f021f0332f1bd40f8b1721d1c32f to your computer and use it in GitHub Desktop.

Select an option

Save AdamCarballo/5fd4f021f0332f1bd40f8b1721d1c32f to your computer and use it in GitHub Desktop.
Unity - Get the WorldToScreenPosition() translated to be used with UI elements inside a Canvas.
using UnityEngine;
public class WorldToScreen : MonoBehaviour {
/// <summary>
/// Get the WorldToScreenPosition translated to be used with UI elements inside a Canvas.
/// </summary>
/// <param name="worldObj">Object in the world to follow.</param>
/// <param name="canvas">Canvas transform that holds the UI object we want to move.</param>
/// <param name="cam">Camera to calculate the screen position. If null will use Camera.main (optional).</param>
/// <returns></returns>
static public Vector2 WorldToCanvasPosition(Transform worldObj, RectTransform canvas, Camera cam = null) {
if (!cam) {
cam = Camera.main;
}
Vector2 ViewportPosition = cam.WorldToViewportPoint(worldObj.position);
Vector2 WorldObject_CanvasPosition = new Vector2(
((ViewportPosition.x * canvas.sizeDelta.x) - (canvas.sizeDelta.x * 0.5f)),
((ViewportPosition.y * canvas.sizeDelta.y) - (canvas.sizeDelta.y * 0.5f)));
return WorldObject_CanvasPosition;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment