unity ugui 坐标位置总结

xiaoxiao2021-02-28  18

Ugui中的transform下有两个位置一个是position,一个是localposition

 

可以简单理解position是世界坐标(位于空间下的某个位置)

Localposition是相对位置是相对与父节点的偏移位置

这些和模型是一个道理

 

白色图片对应Image

红色图片对应Image3

 

两张图片的宽高都是100,两个图片的x距离是100个单位(只用x距离观察,y距离同理)

 

Image(白色图片)属性

Image2(红色图片父节点)属性

Image(红色图片)属性

 

 

Game视图下的分辨率是模拟的具体游戏运行时的屏幕分辨率

代码中的获取方式:Screen.width 和 Screen.height

 

Canvas Scaler中的UI Scale Mode我们一般会选用Scale with Screen的模式,本文中将ReferenceResolution 设置为1280*720

Canvas.GetComponent<CanvasScaler>().referenceResolution此方法可以获得这个值

 

 

 

 

一.Canvas的Render Mode有三种模式,如果项目中没有特殊需求会选择第一种Screen Space-Overlay

 

1.      如果此时屏幕分辨率也是1280*720

那么image3.position.x-image.position.x = 100

 image3.localposition.x-image.localposition.x= 0

2.      如果此时屏幕分辨率变为:1980*1080

image3.position.x-image.position.x = 150

 image3.localposition.x-image.localposition.x= 0

显然如果按照这个距离去做一些ugui位置的处理是不正确的

这个时候我们就需要Canvas.GetComponent<CanvasScaler>().referenceResolutionScreen.widthScreen.height的比例来确定具体的位置

另外通过RectTransformUtility.ScreenPointToLocalPointInRectangle方法来获取的坐标依然可以正确确定二者的位置

 

二,很多时候为了显示界面特效,需要引入camera,Render Mode选择了Screen Space-Camera的模式,这个时候

image3.position.x-image.position.x = 16

image3.localposition.x-image.localposition.x = 0

 

这个时候使用RectTransformUtility.ScreenPointToLocalPointInRectangle转换后的坐标

Vector2 pos;

       Vector2 pos3;

       if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform,image3.transform.position, canvas.GetComponent<Camera>(), out pos3))

       {

            Debug.Log(pos3);

       }

 

       if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvas.transform as RectTransform,image.transform.position, canvas.GetComponent<Camera>(), out pos))

       {

            Debug.Log(pos);

}

pos3.x-pos.x 依然等于100

 

当然也可以得到canvas里设置的camera

Vector3 pos =camera.WorldToScreenPoint(image.transform.position);

Vector3 pos3 =camera.WorldToScreenPoint(image3.transform.position);

将世界坐标position转换为屏幕坐标

Pos3.x-pos.x依然等于100

如果此时实际屏幕分辨率为 1980*1080

那么RectTransformUtility.ScreenPointToLocalPointInRectangle获得的坐标距离依然是100

camera.WorldToScreenPoint转换以后还需要通过Canvas.GetComponent<CanvasScaler>().referenceResolutionScreen.width Screen.height的比例来确定具体的位置

转载请注明原文地址: https://www.6miu.com/read-1750195.html

最新回复(0)