我试图弄清楚 Unity 中的 2D 单位系统是如何工作的。我的游戏屏幕是 800x450 像素。
假设我希望将对象放置在距左上角 20,20 像素的位置(因为它适用于大多数 2D 坐标系)。
我尝试了相机的两种“转换”方法,但都将我的对象放置在非常奇怪的位置,当然不是距左上角 20,20 像素的位置。
我的代码:
Vector3 test1 = Camera.main.ScreenToWorldPoint (new Vector3 (20, 20, 0));
transform.position = test1;
Vector3 test2 = Camera.main.WorldToScreenPoint (new Vector3 (20, 20, 0));
transform.position = test2;
编辑
我做了一个测试,以像素为单位获取屏幕中心。它计算出我的 Z 位置为 10,但我的游戏完全是平的。一切都是 2D,我正在使用正交相机。
代码
Vector3 centerInPixels = Camera.main.WorldToScreenPoint (new Vector3 (0, 0, 0));
// this logs: 450,225,10
// so the pixel center is correct for 800x450, but the z is wrong.
最佳答案
屏幕空间的坐标系是:左下角=(0,0),右上角(像素宽度,像素高度)。据我了解,您试图将对象放置到(20,pixelHeight-20)。那将是
Vector3 test1 = Camera.main.ScreenToWorldPoint (new Vector3 (20, Camera.main.pixelHeight-20, camera.nearClipPlane));
transform.position = test1;
关于c# - 如何计算屏幕位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31116709/