Search code examples
c#unity-game-engineisometric

Having trouble centering a Gizmo in Unity's editor with an Isometric Grid where Z axis serves as Y axis


I'm trying to make the boxes in OnDrawGizmos() center isometrically within each tile. As you can see, I want to know the coordinates of each tile and always have them displayed in the editor. As you can also see, they don't fit well into each tile, and I have no idea how to fix it. Here's the code; I hope you can give me a hand. Thanks in advance.

Image of the result of my code

using UnityEngine;
using UnityEditor;
using UnityEngine.Tilemaps;

[ExecuteAlways]
public class TilemapDebugger : MonoBehaviour
{
    public Grid grid; 

    private void OnDrawGizmos()
    {
        if (grid == null) return;

        Tilemap[] tilemaps = grid.GetComponentsInChildren<Tilemap>();

        foreach (Tilemap tilemap in tilemaps)
        {
            DrawTilePositions(tilemap, Color.green);
        }
    }

    private void DrawTilePositions(Tilemap tilemap, Color color)
    {
        Gizmos.color = color;
        foreach (Vector3Int pos in tilemap.cellBounds.allPositionsWithin)
        {
            TileBase tile = tilemap.GetTile(pos);
            if (tile != null)
            {
                Vector3 worldPos = grid.CellToWorld(pos);

                Handles.Label(worldPos, pos.ToString());

                Gizmos.DrawWireCube(worldPos, grid.cellSize);
            }
        }
    }
}

Solution

  • In order to fit the gizmo to the object, you need to set the transform matrix to the Gizmos.matrix property.

    All transform properties are relative to your object via this matrix. Use Vector3.zero for the position, and Vector3.one for the scale in order to match the object exactly.

    Gizmos.matrix = myObject.transform.localToWorldMatrix;
    Gizmos.DrawCube(Vector3.zero, Vector3.one);
    

    In the case of tile maps, it looks like you can retrieve the matrix through the tile data.

    Gizmos.matrix = tileData.transform;
    

    When you are done creating the gizmos, make sure to set the matrix back to the identity matrix.

    Gizmos.matrix = Matrix4x4.identity;