一 World Space(世界坐标):
我们在场景中添加物体(如:Cube),他们都是以世界坐标显示在场景中的。transform.position可以获得该位置坐标。
1. 代码获取的transform.position都是一致的
无论是3d还是2d,ugui/ngui,父子关系,transform.position都是以场景中心(0,0)的位置开始计算,单位长度也都是一样的。
x轴:左负右正
y轴:上正下负
z轴:里正外负
无论怎样的UI,怎样的层级关系,代码里输出Debug.log(Go.transform.position),输出的总是相对于场景中心(0,0)的距离,也是获取世界坐标的方法。
2. 检视面板的position数值和代码获取的position数值不一致
ngui和ugui的Transform和Recttransform的position显示的数值和代码里获取的transform.position不一致。
ugui btn代码位置position=new Vector(1,0,0),面板显示(31.3,0,0)
ngui btn代码位置position=new Vector(1,0,0),面板显示(371,0,0)
具体比例不是很清楚,可能和测试环境有关。
3. 父子关系的容器,检视面板position和代码获取position不一致
cube和ngui/ugui的子对象的Transform/Recttansform在检视面板中显示的Position数值是相对于父容器的,
但是代码里获取的Transform/RectTransfrom的position是相对于场景中心的。
获取世界坐标:go.transform.position
获取本地坐标:go.tranfrom.localPosition (cube/ngui/ugui,无论层级关系,都是获取的是检视面板中的坐标)
可推断ugui/ngui都是在场景中的一个容器之中,所以检视面板显示的都是相对于父容器的坐标,而不是世界坐标。
二 Screen Space(屏幕坐标):
以像素来定义的,以屏幕的左下角为(0,0)点,右上角为(Screen.width,Screen.height),Z的位置是以相机的世界单位来衡量的。
鼠标位置Input.mousePosition获取的是屏幕坐标。
例如场景分辨率1024x768,如果屏幕被缩小至100x100,那么点击右上角是100x100,而不是分辨率的1024x768。
三 ViewPort Space(视口坐标)
视口坐标是标准的和相对于相机的。相机的左下角为(0,0)点,右上角为(1,1)点,Z的位置是以相机的世界单位来衡量的。
四 绘制GUI界面的坐标系:
这个坐标系与屏幕坐标系相似,不同的是该坐标系以屏幕的左上角为(0,0)点,右下角为(Screen.width,Screen.height)。
坐标转换:
世界坐标 -> 本地坐标:貌似不用转,直接可以position和localPosition获取。
本地坐标 -> 世界坐标:
世界坐标→屏幕坐标:camera.WorldToScreenPoint(transform.position);这样可以将世界坐标转换为屏幕坐标。其中camera为场景中的camera对象。
屏幕坐标→视口坐标:camera.ScreenToViewportPoint(Input.GetTouch(0).position);这样可以将屏幕坐标转换为视口坐标。其中camera为场景中的camera对象。
视口坐标→屏幕坐标:camera.ViewportToScreenPoint();
视口坐标→世界坐标:camera.ViewportToWorldPoint();
父子对象关系:
SetParent(Transform parent, bool worldPositionStays);
false:不保留世界坐标。改变层级关系后,坐标数值不变,位置变化,会相对于父对象移动。
true(默认):世界坐标不变。改变层级关系后,不会移动。
世界空间中的点坐标转换到屏幕坐标(例:枪的准心效果):
screenPos = RectTransformUtility.WorldToScreenPoint(cam, worldPos.transform.position);
屏幕坐标转换到世界坐标(例:鼠标点击产生粒子效果):
Vector3 worldPoint;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(rectTrans, camPos, canvas.worldCamera,out worldPoint))
{
transform.position = worldPoint;
}
屏幕坐标转换到世界空间坐标(射线碰撞位置):
var ray = RectTransformUtility.ScreenPointToRay(worldCamera, screenPos);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
pos.transform.position = hitInfo.point;
}
计算鼠标点击位置到锚点位置的偏差:
Vector3 globalMousePos;
RectTransformUtility.ScreenPointToWorldPointInRectangle(m_DraggingPlane, Input.mousePosition,
eventData.pressEventCamera, out globalMousePos);
offset = transform.position - globalMousePos;
拖动时:
Vector3 globalMousePos;
if (RectTransformUtility.ScreenPointToWorldPointInRectangle(m_DraggingPlane, data.position, data.pressEventCamera, out globalMousePos))
{
transform.position = globalMousePos + offset;
transform.rotation = m_DraggingPlane.rotation;
}