将位置捕捉到大小为 <= 1 的网格

Snapping position to a grid that's size is <= 1

我正在创建一个使用几种不同大小的立方体的基本体素编辑器。

用户有一个滑块,用于控制他们编辑时使用的当前立方体大小,然后在调整时更改要放置的立方体的比例和引导网格。

现在我只剩下要做的就是将放置光标的位置捕捉​​到网格(现在只是想让它工作,稍后再担心面方向计算)。网格大小 <= 1 (0.2, 0.25, 0.33, 0.5, 1).

我可以使用以下方法计算网格位置:

Vector3 currentPos = hit.point; /* where hit.point is the position in space of the cursor on the model*/
Vector3 GridLock = new Vector3(gridScale * Mathf.Round(currentPos.x / gridScale),
                               gridScale * Mathf.Round(currentPos.y / gridScale),
                               gridScale * Mathf.Round(currentPos.z / gridScale));

对于某些网格位置(1、0.33、0.2)效果很好,但对于其他尺寸(0.25、0.5),整个网格偏移了半个单位。

我确定这只是一个基本的数学问题,但我很难解决它:(

感谢任何帮助!

大小为 1 的示例:(黄色立方体是网格固定光标)

大小为 0.5 的示例:(黄色立方体偏移到(我相信)顶部和右侧)

我在 Unity 问答网站上问了同样的问题,我得到了一个有用的答案,这是问题的一部分。 http://answers.unity3d.com/questions/1243447/snapping-to-grid-with-grid-size-of-1.html#answer-1243489

Any ratio could be reduced to a 1 to X ratio

  • so 3 to 4 would be 1 to 1.3333 --> 1/3 off
  • and 3 to 5 would be 1 to 1.6666 --> 2/3 off
  • 4 to 5 would be 1 to 1.25 --> 1/4 off
  • 2 to 3 would be 1 to 1.5 --> 1/2 off
  • and the case above: 2 to 5 would be 1 to 2.5 --> 3/2 off

That means all those cases don't fit together because every X cubes there would be some cubes off

So the problem why it doesn't work in your case is the combination of using the center as well as odd ratios. If you have ratios that fit together they will always be off by half a cube, But some which are off every X cubes might fit nicely to the next larger grid every now and then. This is generally called interference since you have two different frequencies which overlap.

基本上因为我的网格是 2 的幂和 3 的幂值的组合,所以并不是所有的东西都能放在一起。

从答案中还了解到一个巧妙的尝试是你想要取一些数字(例如 1, 2, 3)并从中获得 2 的幂,你可以使用按位左移来做到这一点 1 << num(例如 1<<2 = 41<<3 = 8)。

我遇到的核心问题是使用 Math.Round。即使在切换到使用左下角原点的立方体之后,仍然存在偏移。将其从使用舍入更改为地板 (Math.Floor) 修复了该偏移量。

发生这种情况是因为当您越过网格图块的中点时,它会向上舍入,您将获得下一个网格的位置。