- Home /
World coordinates conversion to cell coordinates in tilemap
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.
Answer by rainbowbeansprout · Jan 20, 2020 at 07:32 PM
Well I feel stupid, I fixed this by replacing Input.mousePosition with Camera.main.ScreenToWorldPoint(Input.mousePosition))
Your answer
Follow this Question
Related Questions
How to get max and min points of a game object on the x and z axis? 3 Answers
Converting world position to local position according to rotation 1 Answer
GameObject.transform.Find().position returning local position for instantiated gameobjects. 0 Answers
Help with positioning of procedurally generating branches and then leaves of a tree. 1 Answer
How to add a teleportation mechanic like ender pearls in Minecraft 0 Answers