Unity关于世界坐标和UI上的坐标转化成屏幕坐标的方式

代码如下

注意要搞清楚当前坐标属于哪种坐标,然后,相对指定的Camera转化

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 关于坐标相对Camera的转换
/// 这里说到的是,有时候UI上的坐标和世界中的坐标想做动画,然后转化的问题
/// </summary>
public class TestCamera : MonoBehaviour
{
    public Camera UiCamera;

    public Camera WorldCamera;
    public Vector3 UIPostion;
    public Vector3 WorldPosion;
    #region 方法1:统一转化为屏幕上的点,这个操作最快捷
    //获得相对自己相机屏幕上的点
    private Vector3 GetScreenPoint(Camera camera ,Vector3 v3)
    {
       return camera.WorldToScreenPoint(v3);
    }

    private void Debug1()
    {
        Debug.Log(GetScreenPoint(UiCamera,UIPostion)+"<>"+GetScreenPoint(WorldCamera,WorldPosion));
    }
    #endregion

    #region 方法2:根据ViewPot转化,也可以达到,虽然繁琐但是原理可以理解下
    //获得所在对应相机视口下,X,Y的比例(0-1 之间的一个曙)
    public  Vector3 GetUguiViewPort(Camera camera,Vector3 v3)
    {
        var point = camera.WorldToViewportPoint(v3);
        return point;
    }
    //获得真正的屏幕上的坐标
    public  Vector3 GetViewPortToPos(Vector2 v2)
    {
        //ViewPort坐标 转 Pos
        return new Vector3(v2.x * Screen.width, v2.y * Screen.height);
    }
    public void Debug2()
    {
        var v1 = GetUguiViewPort(UiCamera, UIPostion);
        var v2 = GetUguiViewPort(WorldCamera, WorldPosion);
        Debug.Log(GetViewPortToPos(v1)+"<>"+GetViewPortToPos(v2));
    }
    #endregion
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}


版权声明:本文为qq_25122429原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。