简体   繁体   中英

Screen Width from screen space into world space Unity3D

I instantiate a gameobject along the X Axis . 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. Should I use ScreenToWorldPoint , I please how can I use it , in my code , I 'm new to unity.

PS: in my project I am using a perspective camera

在此处输入图片说明

It's probably easier to use 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 (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. Obviously, this assumes that your bricks are 1.0 units in size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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