Increasing Inaccuracy Using ScreenPointToRay with Input.mousePosition
I am working on a 3d grid-based prop placement system and I'd like to have objects snap to the nearest grid tile to the mouse. To achieve this, I'm using the following placeholder code to snap the game object cursorFollow to the nearest tile:
RaycastHit testHit; Ray testRay = mainCam.ScreenPointToRay(Input.mousePosition); Physics.Raycast(testRay, out testHit); Vector3 gridPoint = grid.WorldToCell(testHit.point); cursorFollow.transform.position = gridPoint;
Here's a gif of the effect this achieves (the red square is cursorFollow)
As you can see, the further away the cursor gets from the bottom left corner, the more inaccurate the placement of the red cube. I was wondering if anyone understood why this is happening, or an alternative method I can try to make it more accurate. I've been trying to fix this for 3 days and it just seems so bizarre and random :(
Answer by lgarczyn · Jan 07, 2020 at 06:49 PM
Thanks for your well formatted question and animation.
You're basically converting a world position to a cell index, and then using the cell index as a world position.
You need to convert the cell index to a world position again:
cursorFollow.transform.position = gridLayout.CellToWorld(gridPoint);
Your answer
Follow this Question
Related Questions
videoPlayer Script Help Needed 0 Answers
C# - JS problem. 1 Answer
how do i remember a just instantiated prefab as a variable gameobject? 1 Answer
Moving instantiated Objects to target locations 1 Answer
Game Scene lags while starting 0 Answers