如何计算屏幕位置 [英] How calculate screen position
问题描述
我试图找出在Unity二维单位系统是如何工作的。我的游戏画面是800x450像素。
说我希望我的对象被放置在20,20像素从左上角(因为它在大多数二维坐标系的作品)。
我已经试过这两个转换相机的方法,但无论我发生在物体很奇怪的地方,肯定不是从左上角20,20像素。
我的代码:
的Vector3 TEST1 = Camera.main.ScreenToWorldPoint(新的Vector3(20,20,0));
transform.position = test1的;
的Vector3 TEST2 = Camera.main.WorldToScreenPoint(新的Vector3(20,20,0));
transform.position = test2的;
修改
我已经做了一个试验与得到的屏幕的中心像素。据我的计算Z位置为10,但我的比赛是完全平坦。一切都在2D和我使用正交相机。
代码
的Vector3 centerInPixels = Camera.main.WorldToScreenPoint(新的Vector3(0,0,0));
//此日志:450,225,10
//所以像素中心是正确的800x450,但z是错误的。
坐标屏幕空间的系统是:左下角=( 0,0),右上(pixelWidth,pixelHeight)。因此,正如我理解你想放置对象(20,pixelHeight-20)。这将是
的Vector3 TEST1 = Camera.main.ScreenToWorldPoint(新的Vector3(20 Camera.main.pixelHeight-20,相机.nearClipPlane));
transform.position = test1的;
I am trying to figure out how the 2D unit system in Unity works. My game screen is 800x450 pixels.
Say I want my object to be placed at 20,20 pixels from the left top (as it works in most 2D coordinate systems).
I have tried both "convert" methods of the camera, but both place my object at very strange locations, certainly not at 20,20 pixels from the left top.
My code:
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;
EDIT
I have made a test with getting the center of the screen in pixels. It calculates my Z position as 10, but my game is entirely flat. Everything is in 2D and I'm using the orthographic camera.
Code
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.
Coordinate system of screenspace is: bottom-left=(0,0), top-right (pixelWidth,pixelHeight). So as I understand you trying to place object to (20,pixelHeight-20). That would be
Vector3 test1 = Camera.main.ScreenToWorldPoint (new Vector3 (20, Camera.main.pixelHeight-20, camera.nearClipPlane));
transform.position = test1;
这篇关于如何计算屏幕位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!