在Unity中,常用的坐标系统有以下这些:
-
屏幕坐标(Screen Space):屏幕坐标是基于屏幕的坐标系统,是2D坐标系,原点位于屏幕左下角,x轴向右延伸,y轴向上延伸。屏幕坐标通常用于处理用户界面(UI)元素的位置和交互。
-
世界坐标(World Space):世界坐标是游戏世界的坐标系统,它定义了游戏中所有对象的位置和方向。世界坐标是一个三维坐标系,通常使用笛卡尔坐标系,其中x轴表示水平方向,y轴表示垂直方向,z轴表示深度或前后方向。
-
局部坐标(Local Space):局部坐标是相对于对象自身的坐标系统。每个游戏对象都有自己的局部坐标系,原点位于对象的中心点,x轴、y轴和z轴分别表示对象的宽度、高度和深度。局部坐标用于描述对象内部的位置和变换。
-
视图坐标(View Space):视图坐标是相对于摄像机的坐标系统。它是从摄像机的视角来定义对象的位置和方向。视图坐标一般用于进行摄像机空间的渲染和可见性计算。
-
屏幕像素坐标(Screen Pixel Space):屏幕像素坐标是以屏幕像素为单位的坐标系统。原点位于屏幕左下角,x轴和y轴的单位是像素。屏幕像素坐标一般用于处理屏幕上的像素级别的操作,如绘制纹理、图像处理等。
互相转换的方法:
1、世界坐标与局部坐标的互转:
- 世界坐标转局部坐标使用InverseTransformPoint方法,如:
// 世界坐标转局部坐标
Vector3 worldPosition = new Vector3(2, 0, 0);
Transform transform = gameObject.transform;
Vector3 localPosition = transform.InverseTransformPoint(worldPosition);
- 局部坐标转世界坐标使用TransformPoint方法,如:
// 局部坐标转世界坐标
Vector3 localPosition = new Vector3(1, 0, 0);
Transform transform = gameObject.transform;
Vector3 worldPosition = transform.TransformPoint(localPosition);
2、屏幕坐标与世界坐标的互转:
- 屏幕坐标转世界坐标使用ScreenToWorldPoint方法,如:
// 屏幕坐标转世界坐标
Vector3 screenPosition = new Vector3(100, 150, 0);
Camera mainCamera = Camera.main;
Vector3 worldPosition = mainCamera.ScreenToWorldPoint(screenPosition);
- 世界坐标转屏幕坐标WorldToScreenPoint方法,如:
// 世界坐标转屏幕坐标
Vector3 worldPosition = new Vector3(1, 0, 0);
Camera mainCamera = Camera.main;
Vector3 screenPosition = mainCamera.WorldToScreenPoint(worldPosition);
3、视图坐标与屏幕坐标的互转:
- 视图坐标转屏幕坐标使用WorldToScreenPoint方法,如:
// 视图坐标转屏幕坐标
Vector3 viewPosition = new Vector3(0, 0, -10);
Camera mainCamera = Camera.main;
Vector3 screenPosition = mainCamera.WorldToScreenPoint(viewPosition);
- 屏幕坐标转视图坐标ScreenToWorldPoint方法,如:
// 屏幕坐标转视图坐标
Vector3 screenPosition = new Vector3(100, 150, 0);
Camera mainCamera = Camera.main;
Vector3 viewPosition = mainCamera.ScreenToWorldPoint(new Vector3(screenPosition.x, screenPosition.y, 100));
4、屏幕坐标与屏幕像素坐标的互转:
屏幕坐标转屏幕像素坐标,通过分辨率比例转化,如:
// 屏幕坐标转屏幕像素坐标
Vector3 screenPosition = new Vector3(100, 150, 0);
int screenWidth = Screen.width;
int screenHeight = Screen.height;
Vector3 pixelPosition = new Vector3(screenPosition.x * screenWidth, screenPosition.y * screenHeight, 0);
屏幕像素坐标转屏幕坐标,通过分辨率比例转化,如:
// 屏幕像素坐标转屏幕坐标
Vector3 pixelPosition = new Vector3(250, 300, 0);
int screenWidth = Screen.width;
int screenHeight = Screen.height;
Vector3 screenPosition = new Vector3(pixelPosition.x / screenWidth, pixelPosition.y / screenHeight, 0);