Hello,
I made a Snap to grid system.
To make this system, I used Mathf.RoundToInt() function. It works well.
If snapsize is 10, system return value with 10x grid.
But the problem is… I can’t return cross position directly.
It always go through the x- and z-axes.
I thought a method like, when the position is in the green box below, return cross position.
But I failed to make it code…
Vector3 SnapToGrid(Vector3 pos, int snapsize)
{
int x;
int z;
if (pos.x < 0)
{
if (pos.z < 0)
{
x = Mathf.RoundToInt(Mathf.Abs(pos.x / snapsize)) * snapsize * -1;
z = Mathf.RoundToInt(Mathf.Abs(pos.z / snapsize)) * snapsize * -1;
}
else
{
x = Mathf.RoundToInt(Mathf.Abs(pos.x / snapsize)) * snapsize * -1;
z = Mathf.RoundToInt(pos.z / snapsize) * snapsize;
}
}
else
{
if (pos.z < 0)
{
x = Mathf.RoundToInt(pos.x / snapsize) * snapsize;
z = Mathf.RoundToInt(Mathf.Abs(pos.z / snapsize)) * snapsize * -1;
}
else
{
x = Mathf.RoundToInt(pos.x / snapsize) * snapsize;
z = Mathf.RoundToInt(pos.z / snapsize) * snapsize;
}
}
return new Vector3(x, 0, z);
}