以不同的分辨率/长宽比(正字法)在屏幕上定位对象

本文关键字:屏幕 对象 定位 分辨率 | 更新日期: 2023-09-27 17:49:59

老实说,我很迷Unity中的世界、屏幕和视口坐标。
我的问题很简单:在2d游戏中,无论分辨率和屏幕宽高比如何,我如何将对象放置在左下角?

以不同的分辨率/长宽比(正字法)在屏幕上定位对象

你的描述有点模糊,但我认为你是在说这个:

Vector3 screenPos = new Vector3(x,y,z);
camera.ScreenToWorldPoint(screenPos);

作为旁注,2D Unity有特定的算法,也可以搜索。

对于正字法,检查这个可能对你有帮助的统一空间:

http://answers.unity3d.com/questions/501893/calculating-2d-camera-bounds.html

我看到没有人跟进这一点。让我们先弄清楚一些术语:相机。Main =着眼于游戏世界的主摄像头"游戏世界"=你所绘制的整个游戏地图世界点=游戏世界中绝对独特的位置。可以是2D或3D (x,y,z)屏幕点=一个像素在屏幕上的二维x,y位置

所以,当你想要放置一个对象(即改变它的位置)时,你真正要做的是将它放置在游戏世界中的某个地方。如果摄像机恰好看着世界中的那个位置,那么它就会出现在屏幕上。

要找出当前屏幕上的世界的哪些部分,您必须将屏幕点转换为世界点。所以…假设你的对象的大小是20x20,试试这个:

//Attach this script to the item you want "pinned" to the bottom, left corner of the screen
void Update() {
  //fetch the rectangle for the whole screen
  Rect viewportRect = Camera.main.pixelRect; //again, this has nothing to do with the World, just the 2D screen "size", basically
  //now, let's pick out a point on the screen - bottom, left corner - but leave room for the size of our 20x20 object
  Vector3 newPos = new Vector3(viewportRect.xMin + 20, Camera.main.pixelHeight - 20, 0);
  //now calculate where we need to place this item in the World so that it appears in our Camera's view (and, thus, the screen)
  this.transform.position = Camera.main.ScreenToWorldPoint(newPos);
}

我确信98%的信息都是准确的,但如果有人发现错误,请指出来。