- Home /
Accurate Mouse Snap to Grid within Threshold? (Float Rounding Errors)
Im having the same issue as this guy but the convo ended short with no solutions. (http://forum.unity3d.com/threads/snap-to-grid-and-mouse-position.155132/).
I know I need to add a threshold so my mouse can stay within a grid scale of 1 but not sure how to programmably approach it.
could just fix this issue by making the mouse hidden, but Id really like to see how this can be done in a proper way.* I really like the challenge but Ive spent about a day just thinking this through and Im baffled.
I dont know how to explain it further but maybe this image will help. Basically I want the mouse to hover over the entire (1 unit scale) grid. Im aware the behavior is due to rounding of Floats to Ints and that I would need a threshold to "clamp" the mouse to a 1x1 scale grid.
Ray mouseray = Camera.main.ScreenPointToRay(Input.mousePosition) ;
Vector3 mousevector3 = new Vector3 (mouseray.origin.x, mouseray.origin.y, mouseray.origin.z);
//apply grid to mouse hover
if (Physics.Raycast (mouseray.origin, mouseray.direction, out projectorOrigin, 100)) {
//snap to grid 1x1
Vector3 gridpos = new Vector3(Mathf.Floor (projectorOrigin.point.x), Mathf.Floor (projectorOrigin.point.y), Mathf.Floor (projectorOrigin.point.z));
grid.transform.position = new Vector3 (gridpos.x, gridpos.y, gridpos.z);
}
Demonstration:
***Notice how my mouse only moves within the UpperRight of the main box of the actual grid.
Answer by adriandevera · Jun 29, 2015 at 03:52 PM
Solved it.
Rather than Mathf.Round use a function such as this. Make sure to add the variable snapValue!
private float snapValue = 1; //in my case
private float Round( float input )
{
return snapValue * Mathf.Round( ( input / snapValue ) );
}
Result:
Sigh, I always solve my issues 10min after I post on here..
using UnityEngine;
public class Follow$$anonymous$$ouse : $$anonymous$$onoBehaviour
{
public float snapValue = 20;
// Update is called once per frame
void Update()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit, $$anonymous$$athf.Infinity, 1 << Layer$$anonymous$$ask.NameToLayer("Tile")))
{
Vector3 mousePoint = hit.point;
mousePoint.y = 0f;
mousePoint.x = Round(mousePoint.x);
mousePoint.z = Round(mousePoint.z);
transform.position = mousePoint;
}
}
private float Round(float input)
{
return snapValue * $$anonymous$$athf.Round(input / snapValue);
}
}
This is what I did. Raycast to the world from my mouse position. I'm using Adrian's code to round out the X and Z values of the hit.point from my raycast. Then I set the transform.position to the rounded out Vector3.
Your answer
Follow this Question
Related Questions
Gameobject follow mouse on center 1 Answer
Raycast instantiating object to grid 0 Answers
Create Grid and Snap Rigidbodies to Grid 1 Answer
Drag Rigidbody into slots? 2 Answers
Snap object to grid 1 Answer