0
点赞
收藏
分享

微信扫一扫

Unity 世界坐标转UI坐标

妖妖妈 2022-03-30 阅读 54
unity
using UnityEngine;
using UnityEngine.UI;

public static class UGUIUtility
{
public static Vector2 WorldToScreenPoint(Camera worldCam, CanvasScaler scaler, Vector3 worldPoint)
{
if (worldCam == null)
return new Vector2(worldPoint.x, worldPoint.y);

Vector2 screenPoint = (Vector2) worldCam.WorldToScreenPoint(worldPoint);

if (scaler != null)
{
screenPoint.x /= (Screen.width / scaler.referenceResolution.x);
screenPoint.y /= (Screen.height / scaler.referenceResolution.y);
}

return screenPoint;
}

public static Vector2 WorldToScreenPoint(Camera worldCam, Camera uiCam, CanvasScaler scaler, Vector3 worldPoint)
{
if (uiCam == null)
return WorldToScreenPoint(worldCam, scaler, worldPoint);

if (worldCam == null)
return new Vector2(worldPoint.x, worldPoint.y);

Vector2 viewportPoint = (Vector2) worldCam.WorldToViewportPoint(worldPoint);

viewportPoint.x -= 0.5f;
viewportPoint.y -= 0.5f;

Vector3 screenPoint = new Vector3(uiCam.pixelWidth * viewportPoint.x, uiCam.pixelHeight * viewportPoint.y, 0);

if (scaler != null)
{
screenPoint.x /= (Screen.width / scaler.referenceResolution.x);
screenPoint.y /= (Screen.height / scaler.referenceResolution.y);
}

return screenPoint;
}

public static bool WorldToScreenPoint(Camera worldCam, CanvasScaler scaler, Vector3 worldPoint, out Vector2 screenPoint)
{
if (worldCam == null)
{
screenPoint = Vector2.zero;
return false;
}

Vector3 pos = worldCam.WorldToScreenPoint(worldPoint);
if (pos.z < 0)
{
screenPoint = Vector2.zero;
return false;
}

screenPoint = (Vector2) pos;
if (scaler != null)
{
screenPoint.x /= (Screen.width / scaler.referenceResolution.x);
screenPoint.y /= (Screen.height / scaler.referenceResolution.y);
}

return true;
}

public static bool WorldToScreenPoint(Camera worldCam, Camera uiCam, CanvasScaler scaler, Vector3 worldPoint, out Vector2 screenPoint)
{
if (worldCam == null || uiCam == null)
{
screenPoint = Vector2.zero;
return false;
}

Vector3 viewportPoint = worldCam.WorldToViewportPoint(worldPoint);
if (viewportPoint.z < 0)
{
screenPoint = Vector2.zero;
return false;
}

viewportPoint.x -= 0.5f;
viewportPoint.y -= 0.5f;

screenPoint = new Vector2(uiCam.pixelWidth * viewportPoint.x, uiCam.pixelHeight * viewportPoint.y);

if (scaler != null)
{
screenPoint.x /= (Screen.width / scaler.referenceResolution.x);
screenPoint.y /= (Screen.height / scaler.referenceResolution.y);
}

return true;
}
}
举报

相关推荐

0 条评论