简体   繁体   中英

How to Dynamically script viewport rect in unity

I am wanting to dynamically allocate the display of 3 aircraft in unity according to the id of the vehicle in 3 corners of the screen and the main camera view in the top right. I am just unsure how to script the viewport rect as its a piece of the camera prefap.

在此处输入图像描述


EDIT

To do this you have to search camera.rect and you can dynamically allocate it using a basic if statement.

using UnityEngine;

// Change the width of the viewport each time space key is pressed

public class ExampleClass : MonoBehaviour
{
    private Camera cam;

    void Start()
    {
        cam = Camera.main;
    }

    void Update()
    {
        if (Input.GetKey("space"))
        {
            // choose the margin randomly
            float margin = Random.Range(0.0f, 0.3f);
            // setup the rectangle
            cam.rect = new Rect(margin, 0.0f, 1.0f - margin * 2.0f, 1.0f);
        }
    }
}

Search Camera.rect in the api to find the documentation.

here is the simple if statement you could use

private void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.Space))
                    SplitScreen();
}
public void SplitScreen()
    {
        if (StateQueue.TryDequeue(out var stateMsg))

            if (stateMsg.ID == 9)
            {

                // choose the margin randomly
                float margin = Random.Range(0.0f, 0.3f);
                // setup the rectangle
                sensorCamera.rect = new Rect(margin, 0.25f, 1.0f - margin * 2.0f, 0.25f);
                MainCamera.rect = new Rect(margin, 0.50f, 0.0f - margin * 2.0f, 0.25f);

            }
            else if (stateMsg.ID == 10)
            { // choose the margin randomly
                float margin = Random.Range(0.0f, 0.3f);
                // setup the rectangle
                sensorCamera.rect = new Rect(margin, 0.25f, 0.0f - margin * 2.0f, 0.25f);
                MainCamera.rect = new Rect(margin, 0.50f, 0.0f - margin * 2.0f, 0.25f);

            }
            else if (stateMsg.ID == 11)
            {
                // choose the margin randomly
                float margin = Random.Range(0.0f, 0.3f);
                // setup the rectangle
                sensorCamera.rect = new Rect(margin, 0.25f, 0.25f - margin * 2.0f, 0.25f);
                MainCamera.rect = new Rect(margin, 0.50f, 0.0f - margin * 2.0f, 0.25f);
            }
            else
            {
                Debug.Log("this didnt work");
            }

        }

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