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

Unity-世界坐标与屏幕坐标

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

Unity-世界坐标与屏幕坐标

transform.position.x和transform.position.y的值含义是世界坐标。

世界坐标与屏幕坐标有时一样,有时不同,这和Canvas的渲染模式有关。

Canvas共有三种渲染模式

Screen Space - Overlay (此模式UGUI层一直在最上面,其他例如粒子等物体一直在UGUI层的下面)
在该模式下,世界坐标(transform.Position)和屏幕坐标是重合的,即左下为(0,0),右上为(screen.width,screen.height).此时世界坐标和屏幕坐标是一样的。

Screen Space - Camera(此模式UGUI层上面可以设置其他物体的显示,例如粒子显示,UGUI层不是一直在最上面)。

在没有设置Camera时,它和Screen Space - Overlay一样世界坐标,此时世界坐标和屏幕坐标是一样的。(transform.Position)和屏幕坐标是重合的。具体是如下图的设置,2D开发推荐用如下的设置

在设置了Camera时,世界坐标(transform.Postion)和它的Camera相关

在正交相机投影时与Size有关

在透视投影时与FOV和Plane Distance相关

2D主要用正交相机模式

不挂相机时,显示的是从屏幕左下角到该物体的距离,此时此时世界坐标和屏幕坐标是一样的。

挂上相机后,世界坐标的值是显示和相机的位置(相机默认一般是在屏幕的中间)。

这种模式下,想获得屏幕坐标,需要使用camera.WorldToScreenPoint(transform.position);进行转换。

此时转换后的屏幕坐标和之前没挂相机前的数值一致的。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Demo : MonoBehaviour
{
    public Button test;
    public Camera camera;

    void Start()
    {
        Debug.Log("世界坐标:transform.position.x = " + test.transform.position.x);
        Debug.Log("世界坐标转换为屏幕坐标:WorldToScreenPoint.x = " + camera.WorldToScreenPoint(test.transform.position).x);
        Debug.Log("test.GetComponent().anchoredPosition.x = " + test.GetComponent().anchoredPosition.x);
        Debug.Log("test.transform.localPosition.x = " + test.transform.localPosition.x);
    }

}

此时获得屏幕坐标还可以通过camera.ScreenToWorldPoint转回世界坐标

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Demo : MonoBehaviour
{
    public Button test;
    public Camera camera;

    void Start()
    {
        Debug.Log("世界坐标:transform.position.x = " + test.transform.position.x);
        Debug.Log("世界坐标转换为屏幕坐标:WorldToScreenPoint.x = " + camera.WorldToScreenPoint(test.transform.position).x);
        Debug.Log("test.GetComponent().anchoredPosition.x = " + test.GetComponent().anchoredPosition.x);
        Debug.Log("test.transform.localPosition.x = " + test.transform.localPosition.x);

        Vector3 myVector = camera.WorldToScreenPoint(test.transform.position);

        Debug.Log("屏幕坐标转换为世界坐标为:ScreenToWorldPoint.x = " + camera.ScreenToWorldPoint(myVector).x);

    }

}

打印效果如下

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

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

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