曼哈顿六边形网格中瓷砖之间的距离 [英] Manhattan Distance between tiles in a hexagonal grid
问题描述
对于方形网格,图块 A 和 B 之间的欧几里德距离为:
For a square grid the euclidean distance between tile A and B is:
distance = sqrt(sqr(x1-x2)) + sqr(y1-y2))
对于被限制沿着方形网格移动的演员来说,曼哈顿距离是我们必须行进的实际距离的更好度量:
For an actor constrained to move along a square grid, the Manhattan Distance is a better measure of actual distance we must travel:
manhattanDistance = abs(x1-x2) + abs(y1-y2))
如何获得六边形网格中两个瓷砖之间的曼哈顿距离,如下图红线和蓝线所示?
How do I get the manhattan distance between two tiles in a hexagonal grid as illustrated with the red and blue lines below?
推荐答案
我曾经在游戏中设置了一个六边形坐标系,使 y 轴与六边形坐标系成 60 度角.x-轴.这避免了奇偶行区别.
I once set up a hexagonal coordinate system in a game so that the y-axis was at a 60-degree angle to the x-axis. This avoids the odd-even row distinction.
(来源:althenia.net)
在这个坐标系中的距离是:
The distance in this coordinate system is:
dx = x1 - x0
dy = y1 - y0
if sign(dx) == sign(dy)
abs(dx + dy)
else
max(abs(dx), abs(dy))
您可以将 (x', y) 从您的坐标系转换为 (x, y)在这个使用:
You can convert (x', y) from your coordinate system to (x, y) in this one using:
x = x' - floor(y/2)
所以 dx
变成:
dx = x1' - x0' - floor(y1/2) + floor(y0/2)
在使用整数除法实现这一点时要小心四舍五入.在 C 中,int y
floor(y/2)
是 (y%2 ? y-1 : y)/2
.
Careful with rounding when implementing this using integer division. In C for int y
floor(y/2)
is (y%2 ? y-1 : y)/2
.
这篇关于曼哈顿六边形网格中瓷砖之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!