此JavaScript代码是否遵循Midpoint Displacement算法?

ale*_*lex 8 javascript canvas

我正在尝试使用JavaScript并在gamedev.stackexchange.com上推荐使用中点位移算法.canvas

下面的代码生成点,其中数组索引是x位置,其值是y位置.

var createTerrain = function(chops, range) {
    chops = chops || 2;
    range = parseInt(range || 100); 

    if (chops > 8) return;

    var cycle = parseInt(width / chops);    

    for (var i = 0; i <= width; i += cycle) {

        var y = (height / 2) + getRandomNumber(-range, range);

        terrain[i] = y;

    }

    chops *= 2;
    range *= 0.5;
    createTerrain(chops, range);

}
Run Code Online (Sandbox Code Playgroud)

getRandomNumber()的论点是minmax.width并且height各自的canvas.

这会产生类似...... 帆布

它看起来很不稳定,但这可能就是这样.

我有这个算法吗?如果没有,那有什么不对,你能指出我正确的方向吗?

Vin*_*rat 11

我会说它看起来不像中点位移,只是因为每个段都应该有一个规则的X轴长度(你有几乎垂直的段).您是否尝试生成一个简单的4段数组?它是什么样子的?

这是我写的一个简短的教程,你可以看到它在行动:Javascript中的中点算法

源代码:

function Terrain(segmentCount) {
    this.segmentCount = segmentCount;
    this.points = [];
    for (i=0; i<=segmentCount; ++i) {
        this.points[i] = 0;
    }
};

/**
* Generate the terrain using the mid-point displacement algorithm. This is in fact
* a shortcut to the recursive function with the appropriate value to start
* generating the terrain.
*
* @param maxElevation the maximal vertical displacement to apply at this iteration
* @param sharpness how much to attenuate maxElevation at each iteration (lower
*        value means a smoother terrain). Keep between 0 and 1.
*/
Terrain.prototype.generateUsingMidPoint = function(maxElevation, sharpness) {
    this.midPoint(0, this.segmentCount, maxElevation, sharpness);
}

/**
* This is the recursive function to actually generate the terrain. It computes a new height for the point
* between "start" and "end" (the mid-point): averages start and end heights and adds a random
* displacement.
*
* @param maxElevation the maximal vertical displacement to apply at this iteration
* @param sharpness how much to attenuate maxElevation at each iteration (lower
*        value means a smoother terrain). Keep between 0 and 1.
*/
Terrain.prototype.midPoint = function(start, end, maxElevation, sharpness) {
    var middle = Math.round((start + end) * 0.5);
    if ((end-start<=1) || middle==start || middle==end) {
        return;
    }

    var newAltitude = 0.5 * (this.points[end] + this.points[start]) + maxElevation*(1 - 2*Math.random());
    this.points[middle] = newAltitude;

    this.midPoint(start, middle, maxElevation*sharpness, sharpness);
    this.midPoint(middle, end, maxElevation*sharpness, sharpness);
};
Run Code Online (Sandbox Code Playgroud)