您当前的位置: 首页 >  unity

程序员正茂

暂无认证

  • 3浏览

    0关注

    283博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Unity 世界坐标转UI坐标

程序员正茂 发布时间:2018-11-05 12:15:59 ,浏览量:3

一、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();

//设置锚点位置,锚点在左下角
_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();
rt.anchorMin = Vector2.zero;
rt.anchorMax = Vector2.zero;
rt.anchoredPosition = new Vector2(ptView.x * panelShootsPos.rect.width, ptView.y * panelShootsPos.rect.height);

关注
打赏
1660743125
查看更多评论
立即登录/注册

微信扫码登录

0.0414s