如何对此等式进行逆向工程

时间:2018-05-10 13:37:29

标签: algorithm cocos2d-x

我从游戏引擎获得了一个关于如何从交错的瓷砖地图上的平铺位置计算像素位置的算法。

此算法使用像素位置获取图块位置:

float diffX = 0;
if ((int)tilePos.y % 2 == 1)
    diffX = tileSize.width / 2;
return Vec2 (
    tilePos.x * tileSize.width + diffX,
    (mapSize.height - tilePos.y - 1) * tileSize.height / 2);

如何反转此算法以使用像素位置获取平铺位置。

enter image description here

2 个答案:

答案 0 :(得分:0)

将平面划分为围绕具有偶数y坐标的切片的矩形,然后调整结果,如果它在属于另一个切片的四个角三角形之一中。像

这样的东西
# px is pixel x, py is pixel y
x = round(px / width)
y = 2 * round(py / height)
dx = px / width - x
dy = py / height - y / 2
if dx + dy > 0.5:
    y = y + 1
elif dx - dy > 0.5:
    y = y - 1
elif -dx + dy > 0.5:
    x = x - 1
    y = y + 1
elif -dx - dy > 0.5:
    x = x - 1
    y = y - 1

答案 1 :(得分:0)

要解决此问题,此网格将分为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:if [x_,y_] == [0,1]
  • D:if [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;
    }
}

原点位于tile [0,0]的中心,因此x需要递增1.此tile图交错,使得x增加1,宽度为2个矩形,而y增加1个1个高度的矩形,我们需要将x除以2得到实际坐标。

x = ( x + 1 ) / 2;

你有它,这个交错的地图中像素的平铺坐标。