首页 > 解决方案 > Creating a border of cubes around screen

问题描述

I'm trying to dynamically generate a border around the screen / viewport(?) using a standard cube object. Currently, I'm focusing on just generating a border on the left side, but this is proving difficult.

I'm close, with the following example, but I'm sure I have the calculations wrong and I might just be lucky it's working this way. As you can see, the alignment isn't correct on the y axis. My goal is to have 10 perfectly even cubes left and right of the screen, and 5 top and bottom.

public GameObject WallPeice;

// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        BuildWall();
    }
}


public void BuildWall()
{

    var height = Camera.main.orthographicSize * 2.0f * Screen.height / Screen.width;


    var screenSize = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height));

    var mainHeight = height / 20;

    var screenHeight = Math.Abs(-screenSize.y) + screenSize.y;

    var screenDivided = screenHeight / 10;

    for (float i = -screenSize.y - (screenDivided / 2); i < (screenSize.y - (screenDivided / 2)); i+= screenDivided)
    {
        var cube = Instantiate(WallPeice, new Vector3(-screenSize.x, i + (height / 20), 0), new Quaternion(0, 0, 0, 0));

    }



}

Current implementation

标签: unity3d

解决方案


首先,我会使用Camera.ViewportToWorldPoint.

您需要确保不要在角落加倍,跳过已经放置的立方体。

该问题没有提到WallPeice[原文如此] 对象的大小,因此您需要调整比例因子以使多维数据集的大小与它们需要为 10x5 的大小相匹配。

总而言之,它可能看起来像这样:

public void BuildWall()
{

    Camera mainCam = Camera.main;

    Vector3 lowerLeftScreenWorld = mainCam.ViewportToWorldPoint(Vector3.zero);
    Vector3 upperRightScreenWorld = mainCam.ViewportToWorldPoint(new Vector3(1f,1f,0f));

    // 9f because 10 cubes means 9 intervals between them
    distancePerCube = (upperRightScreenWorld.y-lowerLeftScreenWorld.y)/9f;

    float cubeScalingFactor = 1f;

    Vector3 cubeScale = Vector3.one * cubeScalingFactor;

    // left/right walls
    for (float yPos = lowerLeftScreenWorld.y ; yPos <= upperRightScreenWorld.y 
         ; yPos += distancePerCube)
    {
        MakeCube(lowerLeftScreenWorld.x, yPos, cubeScale);
        MakeCube(upperRightScreenWorld.x, yPos, cubeScale);
    }

    // top/bottom walls
    for (float xPos = lowerLeftScreenWorld.x + distancePerCube 
         ; xPos + distancePerCube <= upperRightScreenWorld.x 
         ; xPos += distancePerCube)
    {
        MakeCube(xPos, upperRightScreenWorld.y, cubeScale);
        MakeCube(xPos, lowerLeftScreenWorld.y, cubeScale);
    }

}

private void MakeCube(float xPos, float yPos, Vector3 cubeScale)
{
    GameObject cube = Instantiate(WallPeice, new Vector3(xPos, yPos, 0f), 
            Quaternion.identity);
    cube.transform.localScale = cubeScale;
}

推荐阅读