c# - 两个网格单元之间的距离,没有对角线

标签 c# unity3d math geometry

我已经在一个小项目上工作了几天,一切正常,直到我将我的“ map ”实现更改为与我所基于的游戏 (Dofus) 中的相同(它是一个小 helper 社区)。

基本上,我有一个旋转 45° 的网格布局(见下图),从左上到右下构建。每个单元格作为 xIndex 和 zIndex 来表示它在图像上的位置 (xIndex ; zIndex),我只想获得两个单元格之间的距离,而不是沿对角线移动。

Grid

正如我试图在图片上解释的那样:

  • GetDistanceBetweenTiles(A, B) 应该是 3

  • GetDistanceBetweenTiles(A, C) 应为 5

  • GetDistanceBetweenTiles(B, C) 应为 2

我发现“曼哈顿距离”看起来是我想要的,但它没有给我上面的值。

代码如下:

private int GetDistanceBetweenTiles(MovableObject a, MovableObject b)
{      
    //int dist = Mathf.Abs(a.xIndex - b.xIndex) + Mathf.Abs(a.zIndex - b.zIndex);
    int minX = a.xIndex < b.xIndex ? a.xIndex : b.xIndex;
    int maxX = a.xIndex > b.xIndex ? a.xIndex : b.xIndex;
    int minZ = a.zIndex < b.zIndex ? a.zIndex : b.zIndex;
    int maxZ = a.zIndex > b.zIndex ? a.zIndex : b.zIndex;

    int distX = (maxX - minX);
    int distZ = (maxZ - minZ);

    int dist = Mathf.Abs(maxX - minX) + Mathf.Abs(maxZ - minZ);

    print($"Distance between {a.name} and {b.name} is {dist}");

    return dist;
}

如有任何帮助,我们将不胜感激。

如果有帮助,here is the project working with the first map我做了(但还没有翻译)。

最佳答案

让我们用简单的公式在倾斜的行中创建新坐标:

row = z/2 - x   ("/" for **integer division**)
col = z - row

现在我们可以将曼哈顿距离计算为

abs(row2 - row1) + abs(col2 - col1)

以你为例

x   z       r   c  
4,  2  =>  -3,  5
1,  4  =>   1,  4 
distance = (1-(-3)) + (5-4) = 4 + 1 = 5

解释一下:您的网格旋转了 45 度:

  0  1  2  3  4  5  6  7  8    \column   

              40|41               row -4
           30|31|42|43            row -3   
        20|21|32|33|44|45         row -2
     10|11|22|23|34|35|46|47      row -1  
  00|01|12|13|24|15|36|37|48      row 0
     02|03|14|15|26|27|38         row 1
        04|05|16|17|28            row 2
           06|07|18               row 3

关于c# - 两个网格单元之间的距离,没有对角线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56663971/

相关文章:

c++ - 对以下 c/c++ 解决方案的逻辑解释

javascript - 在不损失精度的情况下,JavaScript 的最大整数值是多少?

c# - 以编程方式滚动带有计时器的 ScrollViewer 变得不稳定

visual-studio - 与 Unity 3D 一起使用时,Visual Studio 中缺少添加引用 - 需要 Npgsql.dll

c# - 在测试中创建 UserManager<T> 的实例

unity3d - 通过 Unity 中的 Oculus 应用程序登录 Google 和 Facebook

c# - 游戏开发 - 如何将 'command line arguments' 传递给 Unity 独立构建?

javascript - 评分系统的数学公式

c# - 如何比较人物(尊重文化)

c# - 如何在后面的代码中使字符串加粗