Sorry, but that’s incorrect. It’s simply the other way around.
To get an object’s position on a grid, you have to divide its position by the grid size.
So in case of a three dimensional grid, you’d calculate the position as follows:
// multiplying AFTER rounding, which will “spread out” the otherwise unit-based grid if multiplying by values greater than 1, and will “squeeze” it if multiplying by values between 0 and 1.
// grid_scaling_size could also be a random value for craziness…
Just throwing in my two cents. I wrote a simple function that runs through an array of Vector2s (Or Vector3s) and returns the index of the position that is currently closest to yours.
int CompareSet( Vector2[] myArray, Vector2 pos ){
int closestIndex = 0;
float smallestDistance = 0.0f;
for( int u = 0; u < myArray.Length; u++ ){
if( u != 0 ){
float thisDistance = (pos - myArray[u]).sqrMagnitude;
closestIndex = ( thisDistance < smallestDistance ) ? u : closestIndex;
smallestDistance = ( thisDistance < smallestDistance ) ? thisDistance : smallestDistance;
}
else smallestDistance = (pos - myArray[u]).sqrMagnitude;
}
return closestIndex;
}
Yes I’d like to second that. I’ve tried to apply this to moving a cube around the terrain according to a grid but ended up with all kinds of errors.
Well, so far all we’ve talked about here is how to round numbers (note: only Errorsatz’s post above does this correctly for a grid size other than one).
To actually apply this, we’d need to know more about what you’re trying to accomplish… I mean, sure, you can snap an object to a grid, but how does it move? Does it move at all? Do you want it to slide smoothly from one grid position to another, and then snap? Or can it just jump from one grid position to the next? Are objects falling in from outer space, and you want them to only land on even grid positions? What?