失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Unity-世界坐标与屏幕坐标

Unity-世界坐标与屏幕坐标

时间:2023-07-03 13:42:52

相关推荐

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<RectTransform>().anchoredPosition.x = " + test.GetComponent<RectTransform>().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<RectTransform>().anchoredPosition.x = " + test.GetComponent<RectTransform>().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);}}

打印效果如下

如果觉得《Unity-世界坐标与屏幕坐标》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。