生成程序平铺背景

时间:2014-06-24 16:14:42

标签: c# unity3d

我正在尝试构建一个带有平铺背景的Shmup游戏,我想在将来生成程序。 但是现在,我甚至无法创造静态背景。无论如何,我都无法让瓷砖填满屏幕。

我正在使用64x64像素的图块。

这里是我使用的代码:

void Start()
{
    m_screenHeight = 1408;
    m_screenWidht = Camera.main.aspect * m_screenHeight;

    float UnitsPerPixel = 1f / 100f;

    Camera.main.orthographicSize = m_screenHeight / 2f * UnitsPerPixel;

    m_horizontalTilesNumber = (int)Math.Floor(m_screenWidht / TileSize);
    m_verticalTilesNumber = (int)Math.Floor(m_screenHeight / TileSize);

    for (int i = 0; i < m_horizontalTilesNumber; i++)
    {
        for (int j = 0; j < m_verticalTilesNumber; j++)
        {
            Instantiate(Tile, Camera.main.ScreenToWorldPoint(new Vector3(TileSize * i, TileSize * j, 0)), Quaternion.identity);
        }
    }
}

以下是它的样子:

enter image description here

在我看来,我在将像素坐标转换为单位时遇到了一些问题,或类似的事情。

此处的任何提示或指示都将受到赞赏。

1 个答案:

答案 0 :(得分:4)

尝试使用以下代码:

/// <summary>
/// Tile prefab to fill background.
/// </summary>
[SerializeField]
public GameObject tilePrefab;

/// <summary>
/// Use this for initialization 
/// </summary>
void Start()
{
    if (tilePrefab.renderer == null)
    {
        Debug.LogError("There is no renderer available to fill background.");
    }

    // tile size.
    Vector2 tileSize = tilePrefab.renderer.bounds.size;

    // set camera to orthographic.
    Camera mainCamera = Camera.main;
    mainCamera.orthographic = true;

    // columns and rows.
    int columns = Mathf.CeilToInt(mainCamera.aspect * mainCamera.orthographicSize / tileSize.x);
    int rows = Mathf.CeilToInt(mainCamera.orthographicSize / tileSize.y);

    // from screen left side to screen right side, because camera is orthographic.
    for (int c = -columns; c < columns; c++)
    {
        for (int r = -rows; r < rows; r++)
        {
            Vector2 position = new Vector2(c * tileSize.x + tileSize.x / 2, r * tileSize.y + tileSize.y / 2);

            GameObject tile = Instantiate(tilePrefab, position, Quaternion.identity) as GameObject;
            tile.transform.parent = transform;
        }
    }
}

您可以在此处找到整个演示项目:https://github.com/joaokucera/unity-procedural-tiled-background