The question is answered, right answer was accepted
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 video. The tile "highlight" position does not correctly match the cursor's position. How can I fix it?
Answer by NoseKills · May 05, 2016 at 09:05 AM
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.
I used Tiled to make the map, and my tiles are 16x16, so 16 pixels per unit, and when I put the map into the scene its pivot is in the top left (I don't know how to change the pivot of the whole map). While reading your answer, I realized that the pivot of the highlight is in the center so I changed it to top left, same as the map, and now it works normally. Thanks for the reply! Thanks also for your tip about negative coordinates :)
I just tried $$anonymous$$athf.FloorToInt() and it's not working correctly. I'll try to fix it. Edit: Fixed it by checking if worldCoordinate is less than 0 or not then do the thing
Follow this Question
Related Questions
Check the if mouse clicked on specific tile 0 Answers
Move object to mouse position 1 Answer
How To Get Tile Cell Position 0 Answers
ScreenToWorldPoint works wrong after updating to 2019.3.5 1 Answer
Render mouse in VR? 1 Answer