一、准备工作
1.创建一个UI图标
2.Cavans属性设置
3.新建一个cube 添加脚本Test
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class Test : MonoBehaviour
{
public Camera cam;
public RectTransform img;
Vector3 pos;
void Start()
{
}
void Update()
{
pos = cam.WorldToScreenPoint(transform.position);
img.anchoredPosition = pos;
}
}
二、测试结果及问题
1.设置屏幕分辨率为1920*1080 正常显示
2.修改分辨率为960*540 位置偏移
三、原因:
这里先介绍下Canvas的组件Canvas Scaler,分辨率自适应神器。通常情况下,UI Scale Mode不同,处理方式也不同。 Scale With Screen Size,这是最常用的一种自适应适配模式,下面会要求填入Reference Resolution(参考分辨率),屏幕的匹配模式Screen Match Mode一般选择Match Width Or Height。width和height设置权重来调节影响比例模式。如下图所示,参考分辨率是1080 x 1920,屏幕分辨率也是1080 x 1920。
举个例子:如参考分辨率设置为1080 x1920, Match设为0,即根据宽度来适配,当屏幕分辨率设置为1536 x 2048时,画布的宽和高也被适配成了1080 x 1440, (即以宽为原则,高等比缩放, 1080 / 1536 x 2048 ,1080 x 1440就是经过Canvas Scaler处理过的宽和高)。反之Match设为1,那便根据高度来适配。
WorldToScreenPoint ,通过它转换出的坐标是基于屏幕分辨率的,那么想要转换成Canvas上的坐标,由于Canvas Scaler的影响,就需要进一步计算,而计算所用的宽和高,就不能用参考分辨率的,要是用经过Canvas Scaler处理过的宽和高。
四、解决方法
处理如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class Test : MonoBehaviour
{
public Camera cam;
public RectTransform img;
Vector3 pos;
void Start()
{
ScreenZoomValue();
}
void Update()
{
pos = cam.WorldToScreenPoint(transform.position);
img.anchoredPosition = new Vector2(pos.x* ScreenUIoffset.x, pos.y* ScreenUIoffset.y);
}
#region 屏幕偏移量换算
public Canvas canvas; //画布
public Vector2 ScreenUIoffset; //屏幕偏移量
public void ScreenZoomValue()
{
//Vector3 screenPos = Camera.main.WorldToScreenPoint(objTrm.position);
RectTransform canvasRtm = canvas.GetComponent<RectTransform>();
//uguiPos.x = screenPos.x * canvasRtm.sizeDelta.x / Screen.width;
//uguiPos.y = screenPos.y * canvasRtm.sizeDelta.y / Screen.height;
ScreenUIoffset.x = canvasRtm.sizeDelta.x / Screen.width;
ScreenUIoffset.y = canvasRtm.sizeDelta.y / Screen.height;
}
#endregion
}
效果:
问题解决