# 坐标转换

已知云端坐标点 A(10,10),需要转换到本地坐标轴下的位置 B?

# 可能的问题

  • 坐标平移
  • 坐标旋转

# 参考

  • Unity 不同空间坐标转换中的矩阵应用_心之凌儿的博客 - CSDN 博客_unity 空间变换

# Unity 中内置转换

using UnityEngine;
 
/// <summary>
/// 坐标转换工具类
/// </summary>
public static class CTUtils
{
    /// <summary>
    /// 世界坐标转屏幕坐标
    /// </summary>
    public static Vector2 World2Screen(Vector3 wp, Camera camera = null)
    {
        if (camera == null)
        {
            camera = Camera.main;
        }
        return camera.WorldToScreenPoint(wp);
    }
 
    /// <summary>
    /// 屏幕坐标转世界坐标
    /// </summary>
    public static Vector3 Screen2World(Vector3 sp, Camera camera = null)
    {
        if (camera == null)
        {
            camera = Camera.main;
        }
        return camera.ScreenToWorldPoint(sp);
    }
 
    /// <summary>
    /// 世界坐标转视口坐标
    /// </summary>
    public static Vector2 World2Viewport(Vector3 wp, Camera camera = null)
    {
        if (camera == null)
        {
            camera = Camera.main;
        }
        return camera.WorldToViewportPoint(wp);
    }
 
    /// <summary>
    /// 视口坐标转世界坐标
    /// </summary>
    public static Vector3 Viewport2World(Vector3 vp, Camera camera = null)
    {
        if (camera == null)
        {
            camera = Camera.main;
        }
        return camera.ViewportToWorldPoint(vp);
    }
 
    /// <summary>
    /// 屏幕坐标转视口坐标
    /// </summary>
    public static Vector2 Screen2Viewport(Vector2 sp, Camera camera = null)
    {
        if (camera == null)
        {
            camera = Camera.main;
        }
        return camera.ScreenToViewportPoint(sp);
    }
 
    /// <summary>
    /// 视口坐标转屏幕坐标
    /// </summary>
    public static Vector2 Viewport2Screen(Vector2 vp, Camera camera = null)
    {
        if (camera == null)
        {
            camera = Camera.main;
        }
        return camera.ViewportToScreenPoint(vp);
    }
 
    /// <summary>
    /// 屏幕坐标转 UI 坐标
    /// </summary>
    public static Vector2 Screen2UI(Vector2 sp, RectTransform rect, Camera camera = null)
    {
        Vector2 uiLocalPos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(rect, sp, camera, out uiLocalPos);
        return uiLocalPos;
    }
 
    /// <summary>
    /// 世界坐标转 UI 坐标
    /// </summary>
    /// <param name="isUIObj"> 是否为 ui 物体 & lt;/param>
    public static Vector2 World2UI(bool isUIObj, Vector3 wp, RectTransform rect, Camera uiCamera, Camera worldCamera = null)
    {
        if (worldCamera == null)
        {
            worldCamera = Camera.main;
        }
        Vector2 screenPos = World2Screen(wp, isUIObj ? uiCamera : worldCamera);
        return Screen2UI(screenPos, rect, uiCamera);
    }
}
更新于 阅读次数

请我喝[茶]~( ̄▽ ̄)~*

Fasty 微信支付

微信支付

Fasty 支付宝

支付宝

Fasty 贝宝

贝宝