想象一下三维空间的六边形空间。
每个图块的坐标为XYZ。 我需要在同一平面上选择给定的单元邻居。 使用SQL看起来像:
$tbDir = $y % 2 == 0 ? -1 : 1;
$result = db_query('SELECT x,y,z FROM {cells} WHERE
x = %d AND y = %d AND z = %d OR
x = %d AND y = %d AND z = %d OR
x = %d AND y = %d AND z = %d OR
x = %d AND y = %d AND z = %d OR
x = %d AND y = %d AND z = %d OR
x = %d AND y = %d AND z = %d OR
x = %d AND y = %d AND z = %d ',
$x, $y, $z,
$x-1, $y, $z,
$x+1, $y, $z,
$x, $y-1, $z,
$x, $y+1, $z,
$x+$tbDir, $y-1, $z,
$x+$tbDir, $y+1, $z);
但是,我不喜欢这样。 也许有人知道更优化的算法? 谢谢!
答案 0 :(得分:4)
这看起来像你可以使用
x BETWEEN $x-1 AND $x+1 AND y BETWEEN $y-1 AND $y+1 AND z = $z
这可能不适用于$ tbDir部分。我将更详细地介绍一下这个案例。
好的,请尝试这个
WHERE x BETWEEN ($x-1 AND $x+1 AND y = $y AND z = $z)
OR (y BETWEEN $y-1 AND $y+1 AND x = $x AND z = $z)
OR (y BETWEEN $y-1 AND $y+1 AND x = $x + $tbDir AND z = $z)
甚至
WHERE ( (x BETWEEN $x-1 AND $x+1 AND y = $y )
OR (y BETWEEN $y-1 AND $y+1 AND x = $x)
OR (y BETWEEN $y-1 AND $y+1 AND x = $x + $tbDir)
)
AND z = $z
答案 1 :(得分:3)
如果您的算法可以使用非正交坐标系,则可以轻松进行映射。在您的情况下,六角形瓦片的与轴平行的部分似乎是垂直的:
/ \ / \ / \
| a | b | c |
\ / \ / \ / \
| d | e | f |
/ \ / \ / \ /
| x | g | h | i
如果您可以接受偏斜的Y轴,那么您可以给a
,d
,g
X坐标0(即Y轴穿过这些图块的中心) 。 (beh
将X == 1,cfi
X == 2,依此类推)。 x
具有坐标(-1,2)。现在你可以像这样移动:
e -> f: x+1,y
e -> d: x-1,y
e -> b: x, y-1
e -> c: x+1,y-1
e -> g: x-1,y+1
e -> h: x, y+1
如您所见,这些动作现在完全独立于y位置。