Game Development Reference
In-Depth Information
How to do it...
To generate a heightmap, perform the following steps:
1. We will start by creating a class called
NoiseMapGenerator
.
2. In its constructor, define a new
FractalSum
instance and store it in a field called
fractalSum
.
3. Next, create a public method called
generateNoiseMap
that takes an integer
parameter called
size
, a float parameter called
frequency
, and an integer para-
meter called
octaves
as inputs.
4. Inside the method, configure
fractalSum
with some of the values and set the
amplitude to
0.5f
as follows:
fractalSum.setFrequency(frequency);
fractalSum.setAmplitude(0.5f);
fractalSum.setOctaves(octaves);
5. Then, define a 2D float array called
terrain
. Its dimension should be [size] x
[size].
6. Now, create a double
for
loop statement and parse through the size of both di-
mensions. Inside the loop, we get the value from
fractalSum
, which is based on
your
x
and
y
coordinates; add
0.5f
to the value. Clamp it to get a value between
0f
and
1f
and set the value in the terrain array as follows:
for(int y = 0; y < size; y++){
for(int x = 0; x < size; x++){
float value = fractalSum.value(x, 0, y) + 0.5f;
value = FastMath.clamp(value, 0f, 1f);
terrain[x][y] = value;
}
}
7. When you're done, call the
ImageGenerator
class to create the PNG image for
us as follows:
ImageGenerator.generateImage(terrain);