首先,unity2d中的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();
// 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("-------------------" );
下面介绍 unity2d 如何获取鼠标位置/如何实现点击哪里就在哪里生成一个新物体/获取点击位置/点击位置转换
void Update () {
screenPosition = Camera.main.WorldToScreenPoint(transform.position);
mousePositionOnScreen = Input.mousePosition;
mousePositionOnScreen.z = screenPosition.z;
mousePositionInWorld = Camera.main.ScreenToWorldPoint(mousePositionOnScreen);
if (Input .GetMouseButtonDown(0)) {
Instantiate (Soldier, mousePositionInWorld , Quaternion.identity);
}
}
2、
transform.position
是我代码所依附的空物体的位置,无所谓在哪,用了WorldToScreenPoint函数之后它的z轴值变为跟camera一样,我们只用z轴的值;
3、
Input.mousePosition
虽然属于屏幕坐标,但它的z轴值不是屏幕坐标系的z轴值,所以我们用
mousePositionOnScreen.z = screenPosition.z;
mousePositionInWorld = Camera.main.ScreenToWorldPoint(mousePositionOnScreen);
Input .GetMouseButtonDown(0)
感知鼠标点击,触发条件;
Instantiate (Soldier, mousePositionInWorld , Quaternion.identity);
生成新物体。