Snap to grid and mouse position

I instantiate an object and snapping its position to a grid, the problem is that i add values to the mouse position to make it snap. I want the object to stay in the middle of the mouse while still snapping to the grid but i can’t find a solution.

Here is the code where im adding the value so it snaps.

// hit.point is the mouse position.
float snap_resolution = 0.5f;
float x_snapped = hit.point.x + (snap_resolution * 0.5f);
x_snapped -= (x_snapped % snap_resolution);
float z_snapped = hit.point.z + (snap_resolution * 0.5f);
z_snapped -= (z_snapped % snap_resolution);				
spawnedClone.position = new Vector3(x_snapped, spawnedClone.position.y, z_snapped);

If you need any more code let me know. ( Although the rest is just some raycasting )

This is not possible. If your object is in the middle of the mouse, then it cant be snapped to the grid (at all mouse positions) . Maybe what your trying to do is make it snap to the grid, only when its a certain distance away (have a jump threshold) that way it could stay in the middle of the mouse until it was almost lined up with the grid, and then snap to the grid. Is that what your after?

Yes thank you that’s exactly what i need. I will try and see if i can make it.

Does anyone have a solution to this? Im having the exact same issue

How would I add a threshold to the grid?

how are you implementing the “grid”? lots of way of doing that, lots of ways of adding the threshold/snapping… going to need to be a little specific

Hey LeftyRighty, thanks for the response but I have solved this yesterday. As for people looking this up in the future, the solution can be found on my Unity Answers Question since I figured theres a lot of empty posts on this topic which is usually overly thought out.

http://answers.unity3d.com/questions/996658/accurate-mouse-snap-to-grid-within-threshold-float.html

As for impkementing the grid, the game is procedural generated in chunks, each grid is a 1x1 to keep things simple. I would simply raycast and do the usual. The only difference is using a different approach to the rounding.

Its entirely configurable as long as your snapValue in my script provided is correct.