gpt4 book ai didi

c# - 从交错等距网格上的坐标获取图 block

转载 作者:行者123 更新时间:2023-12-05 07:37:33 25 4
gpt4 key购买 nike

我无法计算出数学。我有一个交错的 2d 等距网格,将网格单元格转换为世界坐标没问题,但现在我不知道如何反转这个过程。

这是 CellToCoord 方法:

public static Vector2 CellToCoord(int x, int y) {
return new Vector2() {
x = x + ((y % 2) * 0.5f),
y = y * -0.25f
};
}

非常简单,显示网格与 i wanted it to be 完全一样, 我现在想从世界坐标中获取瓦片。

编辑:
Image ,我从 CellToCoord() 方法获得的世界坐标给我一个代表细胞中心的世界位置。

最佳答案

public static Point CoordToCell(Vector2 coord) {
// Divide the cell coordinate the value again (or multiply by -4)
// Then Math.Round() to eliminate any floating point inaccuracies
var cellY = (int)Math.Round(coord.y / -0.25f);

// Armed with the original Integer Y, we can undo the mutation of X (again, accounting for floating point inaccuracies)
var cellX = (int)Math.Round(coord.x - ((cellY % 2) * 0.5f));

return new Point() {
x = cellX,
y = cellY
};
}

这应该会逆转这个过程。我使用 Point 作为整数 X 和 Y 坐标的通用容器,您可以根据需要替换它。

在我看来,最大的问题是 X 突变最初是基于 Y 的整数值,然后您从中存储了一个浮点值。如果没有 Math.Round() 将浮点结果可靠地强制转换回整数值,我无法找到一种方法来扭转这一局面。

更新计算包含给定世界坐标的单元格坐标:

看看你的世界坐标是如何排列的,我们可以看到每个单元格的中心都在给定的对角线上:

  • y = ( x - i )/2 ... 或 ... x - 2y = i
  • y = ( j - x )/2 ...或 ... x + 2y = j

其中 i 和 j 是整数。该图显示了 x - 2y = i 对角线的情况。

Diagram showing diagonal coordinates

使用这些,我们可以获取给定点的世界坐标,计算出 i 和 j,然后将它们四舍五入到最接近的整数,以获得单元格的中心作为 i 和 j。

然后我们可以使用 i 和 j 计算出单元格中心的 x 和 y,并使用我之前发布的函数将它们转换回单元格坐标。

public static Point CoordToCell(Vector2 coord)
{
// Work out the diagonal i and j coordinates of the point.
// i and j are in a diagonal coordinate system that allows us
// to round them to get the centre of the cell.
var i = Math.Round( coord.x - coord.y * 2 );
var j = Math.Round( coord.x + coord.y * 2 );

// With the i and j coordinates of the centre of the cell,
// convert these back into the world coordinates of the centre
var centreX = ( i + j ) / 2;
var centreY = ( j - i ) / 4;

// Now convert these centre world coordinates back into the
// cell coordinates
int cellY = (int)Math.Round(centreY * -4f);
int cellX = (int)Math.Round(centreX - ((cellY % 2) * 0.5f));

return new Point() {
x = cellX,
y = cellY
};
}

我用以下坐标点作为测试用例

{ x = 1.5f, y = -0.25f } => ( 1, 1 )        // Centre of 1, 1
{ x = 1.9f, y = -0.25f } => ( 1, 1 ) // Near the right of 1, 1
{ x = 1.5f, y = -0.374f } => ( 1, 1 ) // Near the bottom of 1, 1
{ x = 1.1f, y = -0.25f } => ( 1, 1 ) // Near the left of 1, 1
{ x = 1.5f, y = -0.126f } => ( 1, 1 ) // Near the top of 1, 1
{ x = 2.5f, y = -0.25f } => ( 2, 1 ) // Centre of 2, 1
{ x = 2f, y = -0.5f } => ( 2, 2 ) // Centre of 2, 2

希望对你有帮助

关于c# - 从交错等距网格上的坐标获取图 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48507216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com