3

我正在从事一个大学 compsci 项目,我需要一些关于视野算法的帮助。我主要工作,但在某些情况下,算法可以穿透墙壁并突出显示玩家不应该看到的墙壁。

void cMap::los(int x0, int y0, int radius)
{ //Does line of sight from any particular tile

for(int x = 0; x < m_Height; x++) {
    for(int y = 0; y < m_Width; y++) {
        getTile(x,y)->setVisible(false);
    }
}

double  xdif = 0;
double  ydif = 0;
bool    visible = false;
float   dist = 0;

for (int x = MAX(x0 - radius,0); x < MIN(x0 + radius, m_Height); x++) {      //Loops through x values within view radius
    for (int y = MAX(y0 - radius,0); y < MIN(y0 + radius, m_Width); y++) {         //Loops through y values within view radius

        xdif = pow( (double) x - x0, 2);
        ydif = pow( (double) y - y0, 2);

        dist = (float) sqrt(xdif + ydif); //Gets the distance between the two points

        if (dist <= radius) {               //If the tile is within view distance,
            visible = line(x0, y0, x, y);       //check if it can be seen.

            if (visible) {                          //If it can be seen,
                getTile(x,y)->setVisible(true);        //Mark that tile as viewable
            }
        }
    }   
}
}

bool cMap::line(int x0,int y0,int x1,int y1)
{
bool steep = abs(y1-y0) > abs(x1-x0);

if (steep) {
    swap(x0, y0);
    swap(x1, y1);
}

if (x0 > x1) {
    swap(x0,x1);
    swap(y0,y1);
}

  int deltax = x1-x0;
  int deltay = abs(y1-y0);
  int error = deltax/2;
  int ystep;
  int y = y0;

  if (y0 < y1)
     ystep = 1;
  else
     ystep = -1;

  for (int x = x0; x < x1; x++) {

      if ( steep && getTile(y,x)->isBlocked()) {
          getTile(y,x)->setVisible(true);
          getTile(y,x)->setDiscovered(true);
        return false;
      } else if (!steep && getTile(x,y)->isBlocked()) {
          getTile(x,y)->setVisible(true);
          getTile(x,y)->setDiscovered(true);
        return false;
      }

     error -= deltay;

     if (error < 0) {
        y = y + ystep;
        error = error + deltax;
     }

  }

  return true;
}

如果有人可以帮助我使第一个被阻止的瓷砖可见但阻止其余的瓷砖,我将不胜感激。

谢谢, Manderin87

4

1 回答 1

2

您似乎正在尝试创建一个光线投射算法。我假设你知道 Bresenham 的台词是如何工作的,所以我会切入正题。

无需检查潜在视野中每个单元的可见性,您只需从 FOV 中心向潜在 FOV 区域(您循环通过的正方形)的最周边的每个单元发射 Bresenham 线。在 Bresenham 线的每一步,您都会检查单元格状态。每条射线的伪代码如下所示:

while (current_cell != destination) {
    current_cell.visible = true;
    if (current_cell.opaque) break;
    else current_cell = current_cell.next();
}

请记住,光线投射会产生大量伪影,在计算出视野后,您可能还需要进行后处理。

一些有用的资源:

于 2011-03-03T00:01:42.187 回答