【问题标题】:How to align tile game objects in a grid如何在网格中对齐平铺游戏对象
【发布时间】:2019-03-12 20:02:35
【问题描述】:

如何将平铺游戏对象与我的平铺地图网格对齐?我有以下设置:

tileSprite: 
  pixels per unit: 32
Grid (created tilemap gameobject):
  Grid component:
    cell size: 32, 32, 0
  GridController script component:
    tileSprite

在 GridController 脚本中:

public class GridController : MonoBehaviour {

    public Sprite tileSprite;

    // Use this for initialization
    void Start () {
        for (int x=0; x<5; x++) {
          for (int y=0; y<5; y++) {
            GameObject tile = new GameObject();
            tile.transform.localPosition = new Vector3(x, y, 0);
            tile.transform.localScale += new Vector3(32, 32, 1);

            SpriteRenderer tile_sr = tile.AddComponent<SpriteRenderer>();
            tile_sr.sprite = tileSprite;
          }
       }
    }
}

我希望它并排放置,但看起来它们之间只有 1 个像素。 IE。我希望 1 个单位等于 32 像素。

我该怎么做?非常感谢您的帮助!

我正在使用 Unity 2017.3.1f1。

【问题讨论】:

    标签: unity3d


    【解决方案1】:

    只需查看您的代码:

    tile.transform.localPosition = new Vector3(x, y, 0);
    

    你直接使用了循环的变量, 但是您需要计算放置瓷砖的位置。 例如(可能不完全正确):

    tile.transform.localPosition = new Vector3(x*32, y*32, 0);
    

    【讨论】:

    • 谢谢,成功了!是否可以将1个单位设置为32像素而无需在代码中计算?
    • 另外,如何将其对齐到左上角而不是网格/画布的中心?
    • 请将您的问题/我的回答标记为解决方案。你问的是一个不同的问题。对齐可能在代码之外完成。 1 个单位 = 1 个单位,你如何解释它是你的行为。你可以为自己定义一些全局常量来使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多