栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 游戏开发 > 其他

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

其他 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

代码如下

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

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// 
/// 关于坐标相对Camera的转换
/// 这里说到的是,有时候UI上的坐标和世界中的坐标想做动画,然后转化的问题
/// 
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()
    {
        
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/906010.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号