Hi,
I’ve been trying for the last 5 days to produce a simple procedural terrain in unity using the diamond square algorithm.
Unfortunately every example (12 at my last count) that I’ve found online is too complicated or has some kind of error in Unity. (i note that apparently the ‘Java’ in Unity is not the same as actual Java code).
My last attempt is from scratch and tries to emulate the example here
My code below starts with 4 corners, then finds the middle point and height, followed by the ‘sides’ (north, east, south, west).
After the first iteration it is supposed to ‘reset’ and find the middle & sides of 4 smaller squares.
As you can see in the picture, the first iteration works ok.
But, I can’t get the ‘reset’ (which moves to the next level of detail) or ‘next’ (which moves to the next square) to actually change their values and start the iteration again.
Can anyone please help or advise?
Code is in JAVA.
function Start () {
// map size
var res = 65;
var step = (res-1);
var tData = GetComponent(Terrain).terrainData;
tData.heightmapResolution = res;
var heights = new float[res, res];
// bumpyness
var bumpyness = 0.03;
var width = res;
var length = res;
var reset = 0;
var next = 1;
//square
//if(reset == 0){
//heights[x,y] = Random.Range(0.1-bumpyness, 0.1+bumpyness);
//}
if(reset == 0){
heights[0,0] = Random.Range(0.1-bumpyness, 0.1+bumpyness);
heights[step,0] = Random.Range(0.1-bumpyness, 0.1+bumpyness);
heights[0,step] = Random.Range(0.1-bumpyness, 0.1+bumpyness);
heights[step,step] = Random.Range(0.1-bumpyness, 0.1+bumpyness);
}
for(next = 1; step*next < res; next++)
{
var x = step*next;
var y = step*next;
var A = heights[x-step, y-step];
var B = heights[x, y-step];
var C = heights[x-step, y];
var D = heights[x, y];
var Middle = (A+B+C+D)/4 + Random.Range(-bumpyness,bumpyness);
heights[x-step/2, y-step/2] = Middle;
var N = (A+B)/2 + Random.Range(-bumpyness,bumpyness);
heights[x-step/2, y-step] = N;
var E = (B+D)/2 + Random.Range(-bumpyness,bumpyness);
heights[x, y-step/2] = E;
var S = (C+D)/2 + Random.Range(-bumpyness,bumpyness);
heights[x-step/2, y] = S;
var W = (A+C)/2 + Random.Range(-bumpyness,bumpyness);
heights[x-step, y-step/2] = W;
print(next);
}
for(reset = 1; step*next >= res && reset < 3; reset++){
print(reset); step = step/2; x = 0; y = 0; next = 1;
}
tData.SetHeights (0, 0, heights);
}