简体   繁体   English

从屏幕空间到世界空间的屏幕宽度Unity3D

[英]Screen Width from screen space into world space Unity3D

I instantiate a gameobject along the X Axis . 我沿X轴实例化一个游戏对象。 Here is my Code: 这是我的代码:

public Transform brick;

void Update()
{
   for (int x = 0; x < Screen.width; x++)
   {
     Instantiate (brick, new Vector3 (x, transform.position.y, 0), Quaternion.identity);
   }
}

But the problem that the value of Screen.width is in pixels so , when I instantiate my object it cross the red line in the picture. 但是Screen.width的值是以像素为单位的问题,因此,当我实例化对象时,它越过了图片中的红线。 Should I use ScreenToWorldPoint , I please how can I use it , in my code , I 'm new to unity. 如果我使用ScreenToWorldPoint,请在我的代码中统一使用它,该如何使用呢?

PS: in my project I am using a perspective camera PS:在我的项目中,我正在使用透视相机

在此处输入图片说明

It's probably easier to use ViewportToWorldPoint . 使用ViewportToWorldPoint可能更容易。 You can use it as follows: 您可以按以下方式使用它:

public Transform brick;

void Update()
{
    Vector3 left = camera.ViewportToWorldPoint(new Vector3(0.0F, 0.0F, camera.nearClipPlane));
    Vector3 right = camera.ViewportToWorldPoint(new Vector3(1.0F, 0.0F, camera.nearClipPlane));

    for (float x = left.x; x < right.x; x = x + 1.0F)
    {
        Instantiate (brick, new Vector3 (x, transform.position.y, 0), Quaternion.identity);
    }
}

Note that your left and right most bricks may still extend past the ends of the screen. 请注意,您的大多数左侧和右侧积木可能仍会延伸超出屏幕末端。 This is because the origin of the brick game objects is likely at the centre of the cube mesh. 这是因为积木游戏对象的原点可能位于立方体网格的中心。 You can modify the for loop as follows to correct this: 您可以按如下所示修改for循环来更正此问题:

for (float x = left.x + 0.5F; x < right.x - 0.5F; x = x + 1.0F)

This way you start 0.5 units from the left and finish 0.5 units from the right. 这样,您从左侧开始0.5个单位,从右侧开始0.5个单位。 Obviously, this assumes that your bricks are 1.0 units in size. 显然,这假设您的积木大小为1.0单位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM