-
-
Save starikcetin/56c850bfcd8e72c91421f8c821ca7949 to your computer and use it in GitHub Desktop.
A small Unity helper class to convert viewport, screen or world positions to canvas space.
This file contains 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 UnityEngine; | |
/// <summary> | |
/// Small helper class to convert viewport, screen or world positions to canvas space. | |
/// Only works with screen space canvases. | |
/// </summary> | |
/// <example> | |
/// <code> | |
/// objectOnCanvasRectTransform.anchoredPosition = specificCanvas.WorldToCanvasPoint(worldspaceTransform.position); | |
/// </code> | |
/// </example> | |
public static class CanvasPositioningExtensions | |
{ | |
public static Vector3 WorldToCanvasPosition(this Canvas canvas, Vector3 worldPosition, Camera camera = null) | |
{ | |
if (camera == null) | |
{ | |
camera = Camera.main; | |
} | |
var viewportPosition = camera.WorldToViewportPoint(worldPosition); | |
return canvas.ViewportToCanvasPosition(viewportPosition); | |
} | |
public static Vector3 ScreenToCanvasPosition(this Canvas canvas, Vector3 screenPosition) | |
{ | |
var viewportPosition = new Vector3(screenPosition.x / Screen.width, | |
screenPosition.y / Screen.height, | |
0); | |
return canvas.ViewportToCanvasPosition(viewportPosition); | |
} | |
public static Vector3 ViewportToCanvasPosition(this Canvas canvas, Vector3 viewportPosition) | |
{ | |
var centerBasedViewPortPosition = viewportPosition - new Vector3(0.5f, 0.5f, 0); | |
var canvasRect = canvas.GetComponent<RectTransform>(); | |
var scale = canvasRect.sizeDelta; | |
return Vector3.Scale(centerBasedViewPortPosition, scale); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment