- Home /
Tilemap coordinates issue - GetTile and SetTile access different tiles
I am using a simple script that reads mouse position and converts it into coordinates for the selected tilemap.
public class MouseHandler : MonoBehaviour
{
public Tilemap tmap;
public Vector3Int previousMousePos = new Vector3Int();
public Vector3Int MouseTilePos;
void Update() {
Vector3Int mousePos = GetMousePosition();
if (!mousePos.Equals(previousMousePos)) {
previousMousePos = mousePos;
MouseTilePos = new Vector3Int(previousMousePos.x, previousMousePos.y, 0);
}
}
Vector3Int GetMousePosition ()
{
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
return tmap.WorldToCell(mouseWorldPos);
}
}
Later on another script uses the value for the GetTile() and SetTile() operations with the same tmap. Problem is, SetTile() sets the correct Tile when given MouseTilePos, but GetTile returns the tile which is positioned several tiles above the cursor position (both x and y coordinates are off). I haven't got any idea how that can occur...
I am using isometric tilemap, cell layout is isometric with z as y.
I can't find the solution in reference documentation and must be doing a simple mistake that I can't see...
Answer by Statement · May 31, 2021 at 10:06 AM
I believe you need to transform the mouse position to a ray then cast that onto the plane of the tilemap before using the mouse position. See this example I recently wrote
Seems to work, thanks, however I am surprised that a direct conversion is not possible with the orthographic camera and the mouse coordinates, without involving colliders...
Well you can use Plane.Raycast as well. That eli$$anonymous$$ates the need for a trigger.
Your answer
![](https://koobas.hobune.stream/wayback/20220613034321im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Quality Reduction only reduces my player sprite quality 0 Answers
How do I read from TilePalette? 0 Answers
Falling Tiles 1 Answer
2D Tilemap prefab brush doesn't paint the tile in the right place 0 Answers