为了解决这个问题,这个网格被分割成像in this image这样的矩形。在这个解决方案中,假设 x 向右增加,y 向下增加。以像素为单位的原点 {0,0} 是浅蓝色圆圈在in this image 所在的位置。这些矩形的坐标看起来像like this。
int px = pixel.x;
int py = pixel.y;
int w = tileSize.width;
int h = tileSize.height;
// find the coord that the pixel is in, in terms of the small rectangles
int x = 2px / w;
int y = 2py / h;
此时,判断像素是否落在in this image这个小矩形中的哪一个。对于这种情况,像素在
- A : 如果 [x_,y_] == [0,0]
- B : 如果 [x_,y_] == [1,0]
- C : 如果 [x_,y_] == [0,1]
- D : 如果 [x_,y_] == [1,1]
知道像素所在的矩形将有助于我们进一步修改 [x,y] 以在此交错平铺地图中找到实际坐标。这里,切线用于确定是否需要增加x或y,以及像素是否在A、B、C或D中的知识。A与D分组,而B与C分组,因为切线值相同.
// relative x and y value in small rectangle
int px_ = px % w;
int py_ = py % h;
// calculate tangent of tile
float tan_tile = h / w;
bool isInfinite = ( 0 == px );
float tan_pixel = 0.0f;
if ( !isInfinite )
{
tan_pixel = py_ / px_;
}
// pixel is in A or D
if ( 0 == ( x + y ) % 2 )
{
// tangent value is infinite
if ( 0 == px )
{
y += 1;
else
{
// For A and D, tangents are flipped along y-axis
if ( -tan_pixel <= -tan_tile )
{
y += 1;
}
}
}
// pixel is in B or C
else
{
// tangent value is infinite
if ( 0 == px )
{
y += 1;
}
else
{
if ( tan_pixel > tan_tile )
{
y += 1;
}
}
}
以上部分可以进一步简化为
-tan_pixel <= -tan_tile
其实是
tan_pixel > tan_tile
因此,比较切线的部分就变成了
// relative x and y value in small rectangle
int px_ = px % w;
int py_ = py % h;
// calculate tangent of tile
float tan_tile = h / w;
if ( 0 == px )
{
y += 1;
}
else
{
float tan_pixel = py_ / px_;
if ( tan_pixel > tan_tile )
{
y += 1;
}
}
原点在图块 [0,0] 的中心,因此 x 需要增加 1。此图块地图是交错的,使得 x 增加 1,宽度为 2 个矩形,而 y 增加 1,高度为 1 个矩形,我们需要将 x 除以 2 得到实际坐标。
x = ( x + 1 ) / 2;
你有它,这个交错地图中像素的平铺坐标。