我已经能够在另一个程序中的编号数组中成功实现中点位移,所以我试图在3D世界中实现它以创建地形但是算法的结果不是我的意思预期
void MidPointDisplacement(float grid[][WIDTH], int left, int right, int top, int bottom, int row, int col)
{
int centreX = (left + right) / 2; //Get the centre of the row
int centreY = (top + bottom) / 2; //Get the centre of the column
if (centreX == left)
{
return;
}
if (centreY == bottom)
{
return;
}
grid[top][centreX] = ((grid[top][left] + grid[top][right]) / 2) + jitter; //define top
grid[bottom][centreX] = ((grid[bottom][left] + grid[bottom][right]) / 2) + jitter; //define bottom
grid[centreY][left] = ((grid[top][left] + grid[bottom][left]) / 2) + jitter; //define left
grid[centreY][right] = ((grid[top][right] + grid[bottom][right]) / 2) + jitter; //define right
grid[centreX][centreY] = ((grid[centreY][left] + grid[centreY][right] + grid[top][centreX] + grid[bottom][centreX]) / 4) + jitter; //Get centre
//decreased the random values
RANDMAX / 2;
RANDMIN / 2;
MidPointDisplacement(grid, centreX, right, centreY, bottom, row, col);
MidPointDisplacement(grid, left, centreX, top, centreY, row, col);
MidPointDisplacement(grid, centreX, right, top, centreY, row, col);
MidPointDisplacement(grid, left, centreX, centreY, bottom, row, col);
}
以上结果如下: 3D Midpoint Displacement
但是我期待这样的地形:
这有什么原因可能吗?我最初认为它可能是抖动但是降低初始值并不能解决这个问题。
float jitter = rand() % (int)(RANDMAX - RANDMIN + 1) + RANDMIN;
抖动是一个全局浮点数,它在RANDMAX(初始值为5.0f)和RANDMIN(初始值为-5.0f)之间取一个随机值。
解决方案:
为了解决上述错误,我删除了我在程序中创建的抖动,而是使抖动成为1的浮点变量。
在MidpointDisplacement函数中,我改变了这个:
grid[top][centreX] = ((grid[top][left] + grid[top][right]) / 2) + jitter; //define top
grid[bottom][centreX] = ((grid[bottom][left] + grid[bottom][right]) / 2) + jitter; //define bottom
grid[centreY][left] = ((grid[top][left] + grid[bottom][left]) / 2) + jitter; //define left
grid[centreY][right] = ((grid[top][right] + grid[bottom][right]) / 2) + jitter; //define right
grid[centreX][centreY] = ((grid[centreY][left] + grid[centreY][right] + grid[top][centreX] + grid[bottom][centreX]) / 4) + jitter; //Get centre
对此:
grid[top][centreX] = ((grid[top][left] + grid[top][right]) / 2) + ((rand() % 256) - 128) / 128.0F * JITTER_RANGE * jitter; //define top
grid[bottom][centreX] = ((grid[bottom][left] + grid[bottom][right]) / 2) + ((rand() % 256) - 128) / 128.0F * JITTER_RANGE * jitter; //define bottom
grid[centreY][left] = ((grid[top][left] + grid[bottom][left]) / 2) + ((rand() % 256) - 128) / 128.0F * JITTER_RANGE * jitter; //define left
grid[centreY][right] = ((grid[top][right] + grid[bottom][right]) / 2) + ((rand() % 256) - 128) / 128.0F * JITTER_RANGE * jitter; //define right
grid[centreY][centreX] = ((grid[centreY][left] + grid[centreY][right] + grid[top][centreX] + grid[bottom][centreX]) / 4) + ((rand() % 256) - 128) / 128.0F * JITTER_RANGE * jitter; //Get centre
然后我再次调用该函数,但是这次我将抖动除以2。
另外,我发现我愚蠢地将centreX和centreY错误地放在了一行(这里没有改变):
grid[centreX][centreY] = ((grid[centreY][left] + grid[centreY][right] + grid[top][centreX] + grid[bottom][centreX]) / 4) + jitter; //Get centre