1. Clear the tile map
map.ClearAllTiles();
2. Get the specified coordinate grid
TileBase tmp = map.GetTile(Vector3Int.zero);
print(tmp);
3. Set to delete tiles
map.SetTile(new Vector3Int(0, 2, 0), tileBase);
map.SetTile(new Vector3Int(1, 0, 0), null);
4. Replace tiles
map.SwapTile(tmp, tileBase);
5. Convert world coordinates to grid coordinates
camera position
Convert screen coordinates to world coordinates
Vector3 mousePos = Input.mousePosition;
Vector3 screenToWorld = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 10));
The 10 on the Z axis corresponds to the position of the camera.
Convert world coordinates to grid coordinates
void Update()
{
//按下鼠标左键
if (Input.GetMouseButtonDown(0))
{
//得到鼠标在屏幕的坐标
Vector3 mousePos = Input.mousePosition;
//屏幕坐标转世界坐标
Vector3 screenToWorld = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 10));
Debug.Log(screenToWorld);
//世界坐标转屏幕坐标
Vector3Int gridPosition = grid.WorldToCell(screenToWorld);
//将鼠标所指位置更换tile
map.SetTile(gridPosition, tb);
}
}
Effect
Click the mouse