Search code examples
c#algorithm3dcoordinate-systems

How to find the closest grid point, for any given point, in a 3D grid that has been rotated around the origin?


Given is an infinite regular 3D grid with a step size of 1, that is aligned with all three spatial axes. If I pick an arbitrary point, finding the closest grid point is easy: I just round each component of the vector the the nearest step.

However, if I rotate the whole grid around the origin, this problem seems to be much more difficult to solve. How would I find the closest grid point for any point, when the grid does not align with the global coordinate system / world space?

I would want this for my Unity project. So if this is feasible to do in C#, that would be amazing. A general explanation of a possible approach would be great too.


Solution

  • As @Berthur and @user3386109 have pointed out in the comments, the solution is as simple as applying the inverse grid rotation to the given point, snapping the vector components to the grid, and then rotating the result back. Thank you.

    Here's a Unity C# snippet of the solution:

    point = Quaternion.Inverse(gridRotation) * point;
    point.x = Snapping.Snap(point.x, grid.stepSize);
    point.y = Snapping.Snap(point.y, grid.stepSize);
    point.z = Snapping.Snap(point.z, grid.stepSize);
    point = gridRotation * point;