how to scale an object in order to fix the screen dimensions

Hi, in my script I instantiate a Game Object, in this case a PLANE.

The dimensions of the plane should be related to the screen size. So for example the plane’s width should be half the screen’s width.

I’m not an expert about the dimension of object, and the “scale” function is a bit tricky.

This is my code, really simple:

        //window
        window_position = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width + 120, Screen.height / 2, 10));
        GameObject window= (GameObject)Instantiate(windowObject, window_position, Quaternion.Euler(-90, 0, 0));
        *window.transform.localScale = new Vector3(4, 1, 6*);

Can you give me some hints, please?

Thanks, I really appreciate it! :slight_smile:

any idea?

I’m not exactly sure what you want but you should look into Screen.width and Screen.height .

Something like:

window.transform.localScale = Vector3(Screen.width/2,Screen.height/2,1);

Hope that helps.

You need to look at the Camera class and all the different projection matrixs. cameraToWorldMatrix and worldToCameraMatrix

It is probably going to end up being some differential and harder math.

I would fake it with the use of camera.WorldToScreenPoint and the gameObjects bounds.
I have made a [5009-cameratest.zip|5009] as an example, with a plane and a camera.

this is the jist of it

        // b = bounds, cam = camera

        // LookAt gives a forward vector towards the object.
        cam.transform.LookAt(b.center);

        // This is the point we use to correct after.
        point = cam.WorldToScreenPoint(go.transform.position + new Vector3(b.extents.x, 0, 0));

        if (correct)
        {
            Vector3 newPosition = transform.position;
            float screenCenter = Screen.width * 0.5f;
            float halfScreenWidth = screenCenter * 0.5f + Screen.width * 0.5f;

            // the plus 1 is so we don't jump back and forth.
            if (point.x > halfScreenWidth + 1)
            {
                newPosition += -cam.transform.forward * Time.deltaTime * speed;
            }
            if (point.x < halfScreenWidth - 1)
            {
                newPosition += cam.transform.forward * Time.deltaTime * speed;
            }

            cam.transform.position = newPosition;
        }