Unity 世界坐标转UI坐标

一、Unity中有四种坐标系

1. World Space(世界坐标):三维空间坐标,浮点数。
2.Screen Space(屏幕坐标):以像素来定义的,以屏幕的左下角为(0,0)点,右上角为(Screen.width,Screen.height),Z的位置是以相机的世界单位来衡量的。
3.ViewPort Space(视口坐标):视口坐标是标准的和相对于相机的。相机的左下角为(0,0)点,右上角为(1,1)点,Z的位置是以相机的世界单位来衡量的。
4.UGUI界面的坐标系:与锚点有关,锚点(在父UI的坐标为(x1, y1))所在位置即为(0,0),X坐标范围为(-x1,Screen.width-x1),y坐标范围为(-y1,Screen.height-y1)。

二、世界坐标转UI坐标

注意:在有些情况下,Cavas的宽高并不与屏幕的宽高相同。

//获取视图坐标
Vector3 ptViewport = Camera.main.WorldToViewportPoint(transform.position);

//获取父UI的长宽,注意不是Screen.Width、Screen.heigt
RectTransform rtParent = _stationInfoScript.transform.parent.GetComponent<RectTransform>();

//设置锚点位置,锚点在左下角
_rectTranformStationInfo.anchoredPosition = new Vector2(ptViewport.x * rtParent.rect.width, ptViewport.y * rtParent.rect.height); 

三、UI坐标以左下角为基点 

Vector3 ptView = m_camera.ScreenToViewportPoint(screenPos);
GameObject hole = Instantiate(prefabBulletHole, panelShootsPos);
RectTransform rt = hole.GetComponent<RectTransform>();
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.zero;
rt.anchoredPosition = new Vector2(ptView.x * panelShootsPos.rect.width, ptView.y * panelShootsPos.rect.height);

  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值