Unity中常见的坐标转换问题汇集
public Transform targetTran;//3D物体
public RectTransform hpTran;//ui
public Camera uiCamera;//相机
public RectTransform canvasTran;//画布
1. UI跟随3d物体
public void WordToUGUI()
{
Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint(Camera.main, targetTran.position);
Vector2 localPoint;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasTran, screenPoint, uiCamera, out localPoint))
{
hpTran.anchoredPosition = localPoint;
}
}
- 3D坐标跟随UI
public void UGUIToWord()
{
Vector2 screenPoint = RectTransformUtility.WorldToScreenPoint(Camera.main, hpTran.position);
//将屏幕坐标转换为视口坐标
Vector3 pos1 = Camera.main.ScreenToViewportPoint(screenPoint);
Vector3 pos2 = Camera.main.WorldToViewportPoint(targetTran.position);
Vector3 pos = new Vector3(pos1.x, pos1.y, pos2.z);
//将合成的视口坐标转换为世界坐标赋值给物体
targetTran.position = Camera.main.ViewportToWorldPoint(pos);
}
3.3d物体跟随屏幕坐标
public void ScreenToWord()
{
//将屏幕坐标转换为视口坐标
Vector3 pos1 = Camera.main.ScreenToViewportPoint(Input.mousePosition);
//将三维物体的世界坐标转换为视口坐标
Vector3 pos2 = Camera.main.WorldToViewportPoint(targetTran.position);
//赋值给一个新的变量
Vector3 pos = new Vector3(pos1.x, pos1.y, pos2.z);
//将合成的视口坐标转换为世界坐标赋值给物体
targetTran.position = Camera.main.ViewportToWorldPoint(pos);
}
大家如果对Unity录屏感兴趣的话可以看下我的Demo,因为目前2019版本unity Recorder报错,目前不太好用.我在Unity2018.1.0版本整理了一下.地址:Unity录屏插件,有Demo