2014-06-24 79 views
3

我正在嘗試使用平鋪背景構建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

在我看來,我有我的轉換像素座標的一些問題單位,或類似的東西。

任何提示或方向在這裏將不勝感激。

+0

請告訴我TileSize的價值?它應該和紋理一樣大小。還要確保相機設置爲拼寫正確。 – Imapler

+0

@Imapler TileSize = 64(像素),相機設置爲拼寫正確。 – Giusepe

回答

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

+0

我只需要添加兩列來填充屏幕,並像魅力一樣工作。 \t \t int rows = Mathf.CeilToInt(mainCamera.orthographicSize/tileSize.y)+ 2; – Giusepe