- Home /
How can i lock an object to grid in my game ?
as i said how can i lock an object to grid in my game ? not in the ENGINE ! in my game
Answer by Hugs Are Drugs · Nov 24, 2012 at 08:29 PM
Recently I was working on a script for placing down objects by clicking in positions and I had to figure this out myself, I'm not sure if you're in UnityScript or C# but I usually work with C# so I'll work with that, if you happen to be working with UnityScript it's not too difficult to convert.
What I decided to use after a bit of research was Mathf.round, this converts a float into an int and if it's given a decimal .50 it will convert into the closest even number, never an odd. Here's how I did it and how you'll probably do it too.
Vector3 x;
void Start () {
x = Vector3 (1.51, 7.34, 1.564);
x.x = Mathf.Round (x.x);
x.y = Mathf.Round (x.y);
x.z = Mathf.Round (x.z);
print (x);
}
This code will output (2, 7, 2).
You can also round to the nearest .50 with this method.
Vector3 x;
void Start () {
x = Vector3 (1.51, 7.34, 1.564);
x.x = Mathf.Round (x.x * 2) / 2;
x.y = Mathf.Round (x.y * 2) / 2;
x.z = Mathf.Round (x.z * 2) / 2;
print (x);
}
This code will output (1.5, 7.5, 1.5).
You could also round to the nearest .25 by replacing the 2 and / 2 with 4 and / 4.
Hope this helped.