微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#-生成程序平铺背景

我正在尝试构建一个平铺背景的Shmup游戏,我希望该游戏可以在将来生成该程序.
但是现在,我什至无法建立静态背景.不管怎样,我都无法将磁贴填满整个屏幕.

我正在使用64×64像素的图块.

这是我正在使用的代码

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);
        }
    }
}

看起来像这样:

在我看来,将像素坐标转换为单位或类似问题时遇到问题.

在这里的任何提示或指示,将不胜感激.

解决方法:

尝试在下面使用此代码

/// <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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐