首先,unity2d中的camera有四大坐标系你需要了解清楚:
官方对unity camera的描述:
Description
A Camera is a device through which the player views the world.
A screen space point is defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight). The z position is in world units from the camera.
A viewport space point is normalized and relative to the camera. The bottom-left of the camera is (0,0); the top-right is (1,1). The z position is in world units from the camera.
A world space point is defined in global coordinates (eg. Transform.position).
翻译:
摄像机是玩家观看世界的入口。
屏幕空间:以像素为单位,屏幕的左下为(0,0);右上是(PixelWidth,pixelHeight),z轴的值与camera相同。注意:鼠标位置坐标属于屏幕坐标,但Input.mousePosition获得的位置坐标是世界坐标,z轴值为0,需要转换,见下文。
视口空间:与camera相关的归一化坐标,相机的左下角为(0,0)点,右上角为(1,1)点,z轴的值与camera相同。(用的不多
世界空间:普遍坐标系,是场景中物体的3D实际位置。注意:transform.position 的值默认是代码所贴附的物体的位置。
第四个坐标系是 绘制GUI界面的坐标系:这个坐标系与屏幕坐标系相似,不同的是该坐标系以屏幕的左上角为(0,0)点,右下角为(Screen.width,Screen.height)。
他们之间有转换关系,如下:
世界坐标→屏幕坐标:camera.WorldToScreenPoint(transform.position);这样可以将世界坐标转换为屏幕坐标。其中camera为场景中的camera对象。
屏幕坐标→视口坐标:camera.ScreenToViewportPoint(Input.GetTouch(0).position);这样可以将屏幕坐标转换为视口坐标。其中camera为场景中的camera对象。
视口坐标→屏幕坐标:camera.ViewportToScreenPoint();
视口坐标→世界坐标:camera.ViewportToWorldPoint();
转换函数一共六种,详见下面的测试代码:
// print("Input.mousePosition: " + Input.mousePosition );
// print("Input.mousePosition world to viewport: " + Camera.main.WorldToViewportPoint(Input.mousePosition ));
// print("Input.mousePosition world to screen: " + Camera.main.WorldToScreenPoint(Input.mousePosition));
// print("Input.mousePosition Viewport To Screen: " + Camera.main.ViewportToScreenPoint(Input.mousePosition ));
// print("Input.mousePosition Viewport To World: " + Camera.main.ViewportToWorldPoint(Input.mousePosition));
// print("Input.mousePosition Screen To Viewport " + Camera.main.ScreenToViewportPoint(Input.mousePosition ));
// print("Input.mousePosition Screen To World: " + Camera.main.ScreenToWorldPoint(Input.mousePosition));
// print("-------------------" );