I’m trying to manually set tiles in a tilemap within my script, and then position gameobjects on-screen relative to those tiles. I’m running into an issue where converting between cell coordinates and world position of a mouse press (Input.mousePosition) just returns the same number. Here’s my code so far:
public class View : MonoBehaviour {
public Tilemap tilemap;
public List<Player> players;
private BoardTile selectedTile;
private model model;
// add tile sprites to the tilemap
public void setTiles() {
Vector2Int size = model.BoardSize;
for (int x = 0; x < size.x; x++) {
for (int y = 0; y < size.y; y++) {
tilemap.SetTile(new Vector3Int(x, y, 0), model.getSprite(x, y));
}
}
}
// change player GameObjects' positions
public void movePlayers() {
foreach (Player p in players) {
Vector2Int loc = p.CellCoordinates;
p.GameObject.transform.position = tilemap.GetCellCenterWorld(new Vector3Int(loc.x, loc.y, 0));
Debug.Log(x + ", " + y + ", " + tilemap.GetCellCenterWorld(new Vector3Int(loc.x, loc.y, 0))); // if there's a player on tile (0, 0) this prints 0, 0, (0.5, 0.5, 0)
}
}
void Update() {
// if the player presses on a tile, select it
if (Input.GetMouseButtonDown(0)) {
Vector3 pos = Input.mousePosition;
Debug.Log(pos); // if i click on the center of tile (0, 0) it prints (423.2, 217.4, 0.0)
Vector3Int cell = tilemap.WorldToCell(pos);
selectedTile = model.TileAt(cell.x, cell.y);
Debug.Log(cell); // this prints (423, 217, 0)
}
}
}
So transform.position for my player GameObjects seems to be relative to the tilemap’s cell coordinates, the mouse press is relative to the distance from the bottom left corner of my screen, and the methods for converting between the two (ie Tilemap.WorldToCell, Tilemap.CellToWorld, Transform.LocalPosition) aren’t working the way I thought they would.
I’m sure there’s something stupid I’m missing but the documentation for Tilemap and Transform and Input haven’t been helpful so far and this has been stumping me for days.