Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the center of a grid's cell - unity

I'm working on an isometric game with Unity and I need to know the centre of the cell in the world coordinates. I'm using the tilemap's GetCellCenterWorld() method, but it gives me back bad results. Here is what I expect to be the centre of the cell (basically the logical centre), but here is what Unity gives back (the top vertex of the cell?). I believe it has something to do with the sprite's pivot point (now set to its top centre) or the cell anchor in the tilemap's properties (I set it to (1,1)).

Here's the code I use to "select" the tiles:

public class GridSelection : MonoBehaviour
{
    public Tilemap tilemap;
    public Transform selector;

    void Update()
    {
        Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        worldPos.z = 0;

        Vector3Int tilemapPos = tilemap.WorldToCell(worldPos);
        selector.position = tilemap.GetCellCenterWorld(tilemapPos);
    }
}

How do I get the actual middle point of the cell?

like image 574
thelukaszns Avatar asked Oct 14 '25 14:10

thelukaszns


2 Answers

Okay, I think I found what the issue was.

If anyone has the same problem, here's how I resolved it:

  1. Set the sprite pivot point to the place you want the middle of the cell to be (in my case, the centre of the grass section)
  2. Set tile anchor back to (0.5, 0.5)
  3. Use the GetCellCenterWorld() method normally

The code I've posted in the question works just fine now.

like image 197
thelukaszns Avatar answered Oct 17 '25 04:10

thelukaszns


[SerializeField] private Tilemap map;
private Camera camera;
[SerializeField] private Transform playerTransform;

void Start(){
    camera = Camera.main;
}

// Update is called once per frame
void Update(){
    if (Input.GetMouseButtonDown(0)){
        var worldPos = camera.ScreenToWorldPoint(Input.mousePosition);
        Vector3Int tilemapPos = map.WorldToCell(worldPos);
        playerTransform.position = map.CellToWorld(tilemapPos);
        Debug.Log(tilemapPos);
    }
}

playerTransform.position = map.CellToWorld(clickedCellPosition);

Just convert it back and provide tilemapPos

like image 41
Mopto Avatar answered Oct 17 '25 05:10

Mopto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!