Tile based mouse cursor

I want to have a “tile based” (cell) mouse cursor in my game. I have this in my script:

`void Update () {
Vector3 worldCoords = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        Vector3 newPos = new Vector3((int)worldCoords.x , (int)worldCoords.y, gameObject.transform.position.z);
        Debug.Log(worldCoords.x + " " + worldCoords.y);

        gameObject.transform.position = newPos;
	}`

But as you can see in this 1. The tile “highlight” position does not correctly match the cursor’s position. How can I fix it?

It would be easier to answer if we could see how your tiles are pivoted. However I suspect they are center pivoted and this combined with casting the mouse coordinates to int (rounding them always towards zero) is what is causing the issue. Looking at the code and video, I guess your tile size is 1x1 units…

If you have a centered tile at 0,0, its right edge at +0.5. Since you cast to int, even when your cursor is at 0.9, the tile position rounds to 0. You have to add half of the tile size to your cursor position before casting to make sure anything over .5 rounds to the next integer.

If you need this to work for negative coordinates, you should use Matf.FloorToInt() instead of casting. Otherwise e.g. anything from -0.9 to +0.9 will round to 0, and you will get a bug.