Perlin noise is how games get rolling hills instead of TV static. It’s a function that turns a position into a smooth, random-looking number: nearby points get similar values, far-apart points get unrelated ones, and the same seed always gives the same world. Minecraft’s terrain, cloudy skies, wobbling torches and camera shake all lean on it.
Ken Perlin created it in 1983, after working on the effects for Disney’s TRON, because computer graphics looked too clean and machine-made. It later earned him an Academy Award for Technical Achievement. In this tutorial, you’ll build Perlin noise from scratch, see inside it with seven live labs, and turn it into a seeded terrain height map you can scroll forever. The code comes in JavaScript, C#, C++ and pseudocode, and the JavaScript is the exact code running in every lab on this page.
What Is Perlin Noise?
Picture a mattress with springs under it. Under each spring someone has tilted a little board, some pointing uphill to the east, some to the north-west, at random. Lay a sheet over the whole thing and smooth it down. The sheet rises and falls in gentle hills, but you can’t predict where the next hill is. That sheet is Perlin noise.
Formally, Perlin noise is a gradient noise. A grid covers space, and every grid corner gets a pseudo-random gradient (a direction the surface slopes). To find the value at any point, you measure how much each nearby corner’s slope “points at” the point, then blend those numbers with a smooth curve. The result is continuous, has no sharp edges, and repeats only when you want it to.
You’ve seen it all over the place:
- Film effects: marble, fire and smoke textures since the 1980s, which is why Perlin’s award came from the film academy.
- Game terrain: Minecraft’s height and biome generators are built from Perlin noise, according to the Minecraft Wiki.
- Game engines: Unity has
Mathf.PerlinNoise, and Godot’sFastNoiseLitehas aTYPE_PERLINsetting.
Let’s start with the difference that matters most: plain random numbers versus coherent noise.
Lab: Random vs Value vs Perlin
👉 Try this: switch to 1D slice and compare the three lines. White noise jumps all over the place, while value and Perlin noise drift smoothly. Back in 2D image, tick Show grid. Value noise looks blocky, with its brightest and darkest spots stuck to grid corners. Perlin noise hides the grid much better, because every corner is exactly 0 and the highs and lows land in between.
Why Use Perlin Noise in Games?
- Terrain: read the noise as height and you get continents, coastlines and mountain ranges. That’s Lab #4.
- Textures without textures: clouds, marble, wood grain, lava and fog, generated at any resolution, so nothing pixelates up close.
- Natural motion: feed time into 1D noise and you get a flickering torch, swaying grass or a drifting boat. Smooth noise is also the classic trick for camera shake: Bevy’s screen-shake example, which follows Squirrel Eiserloh’s GDC 2016 talk on camera math, drives every offset with Perlin noise.
- Placement: where noise is high, spawn trees, ore or enemies. Clusters and clearings appear on their own.
- Endless, shareable worlds: noise is a function of position, so you can generate any chunk in any order, and the same seed rebuilds the same world for every player.
Behind the Scenes: The Math of Perlin Noise
You don’t need much math to use Perlin noise, but three ideas make the code make sense:
- Dot products: the dot product of a corner’s gradient and the offset from that corner to your point says how far the point sits “uphill” along that gradient. Each corner proposes a height that way.
- Interpolation: the four proposals (eight in 3D) get blended, weighted by how close the point is to each corner.
- A fade curve: the blend weights go through an S-shaped curve, so the surface flattens out near every corner and the cells join without creases.
You’ll poke at all three in Lab #1. For a gentle video walkthrough, bookmark The Coding Train’s Perlin noise playlist.
Step-by-Step Lab #1: Build a Perlin Noise Generator
Our Perlin class needs two parts: a seeded random number generator to shuffle its lookup table, and the noise function itself. We’ll build the generator first.
Step 1: Seeded Randomness
Games need randomness you can repeat. If a player shares seed 123456, everyone should get the same mountains, and when a bug report says “the river runs through the castle on seed 42,” you need to see that river too. Math.random() can’t do that, because you can’t seed it.
Our SeededRandom class is a tiny Lehmer generator (the classic “minimal standard” from Park and Miller): multiply by 16807, take the remainder modulo 2³¹ − 1, repeat. It isn’t good enough for cryptography, but it’s fast, and it gives identical numbers in JavaScript, C# and C++.
/**
* Defines a SeededRandom class for generating pseudo-random numbers based on an initial seed.
* This is useful for situations where you need reproducible sequences of random numbers.
*/
class SeededRandom {
/**
* Constructor for the SeededRandom class.
* Initializes a new instance with a seed value.
*
* @param {number} seed - The initial seed value for the pseudo-random number generator.
* The seed ensures the sequence of generated numbers is reproducible.
*/
constructor(seed) {
// The modulus operator ensures the seed value stays within the range of positive 32-bit integers.
// 2147483647 (2^31 - 1) is the largest signed 32-bit integer, and it's prime, which is why linear congruential generators like this one use it.
this.seed = seed % 2147483647;
// If the seed is not positive, adjust it to ensure it is within the range 1 to 2147483646.
// This adjustment is necessary because a seed of 0 would produce a sequence of zeros, reducing randomness.
if (this.seed <= 0) this.seed += 2147483646;
}
/**
* Generates the next pseudo-random number in the sequence.
*
* @returns {number} The next pseudo-random number, ensuring it falls within the 32-bit integer range.
*/
next() {
// Multiplies the current seed by 16807 (a primitive root modulo 2147483647, which ensures a full cycle of numbers)
// and takes the modulus to ensure the result remains within 32-bit integer size.
// This specific multiplier is part of the minimal standard random number generator.
return this.seed = this.seed * 16807 % 2147483647;
}
/**
* Generates a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive).
*
* @returns {number} The next pseudo-random floating-point number.
*/
nextFloat() {
// Calls next() to get a new pseudo-random integer, subtracts 1 to make it start from 0,
// and divides by 2147483646 to normalize the result to the range [0,1).
return (this.next() - 1) / 2147483646;
}
}
using System;
/// <summary>
/// A pseudo-random number generator class that uses a linear congruential generator (LCG) algorithm,
/// allowing for reproducible sequences of random numbers given an initial seed.
/// </summary>
public class SeededRandom
{
// The current state of the generator, which will evolve as new numbers are generated.
private long seed;
// Constants for the linear congruential generator algorithm. The values of these constants are crucial
// for the quality of the pseudo-random numbers generated.
// The multiplier value 'a'. 16807 is Park and Miller's "minimal standard" multiplier, the same one the
// JavaScript version uses, so the same seed gives the same sequence in both languages.
private const long a = 16807;
// The increment value 'c'. It is set to 0 for this implementation, defining it as a multiplicative LCG.
private const long c = 0;
// The modulus value 'm'. It's set to 2^31 - 1, which is a Mersenne prime that helps achieve a full period for the LCG.
private const long m = 2147483647;
/// <summary>
/// Constructs a new instance of the SeededRandom class with a given initial seed.
/// </summary>
/// <param name="seed">The initial seed value for the pseudo-random number generator.</param>
public SeededRandom(int seed)
{
// Keep the seed between 1 and m - 1, like the JavaScript version. A seed of 0 would make every
// number 0, and a negative seed would make Next() return negative numbers.
this.seed = seed % m;
if (this.seed <= 0) this.seed += m - 1;
}
/// <summary>
/// Generates the next pseudo-random number in the sequence as an integer.
/// </summary>
/// <returns>A pseudo-random integer.</returns>
public int Next()
{
// Updates the seed by applying the linear congruential generator formula
// and returns the new seed as the next number in the sequence.
seed = (a * seed + c) % m;
return (int)seed;
}
/// <summary>
/// Generates a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive).
/// </summary>
/// <returns>A pseudo-random double.</returns>
public double NextFloat()
{
// Calls Next() to get a pseudo-random integer from 1 to m - 1, subtracts 1 so it starts at 0,
// and divides by m - 1 to normalize the result to the range [0, 1), exactly like the JavaScript version.
// It returns a double because a float can't store numbers this big precisely: as a float,
// 2147483646 / 2147483647 rounds up to exactly 1.0.
return (Next() - 1) / (double)(m - 1);
}
}
#include <algorithm>
#include <cmath>
#include <iostream>
#include <vector>
/// A pseudo-random number generator class based on a linear congruential generator (LCG) algorithm.
/// This class allows generating a sequence of pseudo-random numbers from a seed value,
/// ensuring reproducible outcomes which are useful for simulations, testing, and gaming.
class SeededRandom {
private:
// Current seed value, evolves with each call to Next() or NextFloat().
// These are 'long long' because plain 'long' is only 32 bits on Windows (MSVC),
// and a * seed needs about 46 bits.
long long seed;
// The multiplier 'a'. 16807 is Park and Miller's "minimal standard" multiplier, the same one the
// JavaScript version uses, so the same seed gives the same sequence in both languages.
static const long long a = 16807;
// The increment 'c'. It is set to 0 in this implementation, defining it as a multiplicative LCG.
static const long long c = 0;
// The modulus 'm'. Using 2^31 - 1 (a Mersenne prime) as the modulus helps in achieving a full period
// for the generated pseudo-random sequence, maximizing the sequence's length before it repeats.
static const long long m = 2147483647;
public:
/// Constructor that initializes the pseudo-random number generator with a seed value.
/// @param seed Initial seed value for generating numbers.
SeededRandom(int seed) : seed(seed % m) {
// Keep the seed between 1 and m - 1, like the JavaScript version. A seed of 0 would make every
// number 0, and a negative seed would make Next() return negative numbers.
if (this->seed <= 0) this->seed += m - 1;
}
/// Generates the next number in the sequence of pseudo-random numbers.
/// @return The next pseudo-random number as an int.
int Next() {
// Calculates the next seed value using the linear congruential generator formula.
// The use of static_cast<int> ensures the result is properly typed as an integer.
seed = (a * seed + c) % m;
return static_cast<int>(seed);
}
/// Generates a floating-point number between 0 (inclusive) and 1 (exclusive) based on the pseudo-random sequence.
/// @return A pseudo-random double between 0 and 1.
double NextFloat() {
// Takes a pseudo-random integer from 1 to m - 1, subtracts 1 so it starts at 0, and divides by m - 1
// to normalize the result to the range [0, 1), exactly like the JavaScript version.
// It returns a double because a float can't store numbers this big precisely: as a float,
// 2147483646 / 2147483647 rounds up to exactly 1.0.
return (Next() - 1) / static_cast<double>(m - 1);
}
};
// Defines a class named SeededRandom for generating pseudo-random numbers based on an initial seed value.
// This class uses a linear congruential generator (LCG) algorithm to produce a sequence of pseudo-random numbers,
// which is useful for scenarios requiring reproducible randomness, such as simulations or game logic.
CLASS SeededRandom
// Constructor method initializes a new instance of SeededRandom with a given seed.
// The seed value is used to start the sequence of pseudo-random numbers.
METHOD constructor(seed)
// Adjusts the seed to ensure it is within the range of positive 32-bit integers,
// using 2147483647 (2^31 - 1, a prime and the largest signed 32-bit integer) as the modulus.
this.seed = seed MOD 2147483647
// Ensures the seed value is positive, adjusting it if necessary.
// This adjustment is crucial because a non-positive seed would impair the randomness.
IF this.seed <= 0 THEN
this.seed = this.seed + 2147483646
END IF
END METHOD
// Generates the next number in the pseudo-random sequence.
METHOD next()
// Updates the seed using a specific multiplier (16807) and modulus (2147483647),
// which are common parameters for LCG algorithms to ensure good distribution and cycle length.
this.seed = (this.seed * 16807) MOD 2147483647
// Returns the updated seed as the next number in the sequence.
RETURN this.seed
END METHOD
// Generates a floating-point number between 0 (inclusive) and 1 (exclusive).
METHOD nextFloat()
// Calls the next() method to generate a new pseudo-random integer, then normalizes
// this value to a floating-point number in the range [0, 1) by dividing by the maximum possible value.
// Subtracting 1 from the next() result before the division ensures the result is strictly less than 1.
RETURN (this.next() - 1) / 2147483646
END METHOD
END CLASS
Step 2: The Perlin Class
The Perlin class turns a seed into a noise function. Here’s what each part does:
- Constructor: fills a table with the numbers 0 to 255, shuffles it with
SeededRandom(a Fisher–Yates shuffle), then doubles it to 512 entries so lookups never run off the end. This permutation table is the noise’s whole personality: change the seed and you get a different table, and a different world. fade(t): Ken Perlin’s S-curve, 6t⁵ − 15t⁴ + 10t³. It turns a straight 0-to-1 ramp into one that eases in and out.lerp(t, a, b): linear interpolation, the blend betweenaandbby weightt. Note the order:tcomes first, as in Perlin’s reference code.grad(hash, x, y, z): uses the low 4 bits of a hash from the table to pick one of 12 gradient directions, and returns its dot product with the offset(x, y, z).noise(x, y, z): finds the cell the point is in, hashes its 8 corners, computes the 8 dot products and blends them withfade()andlerp(). The result is roughly between −1 and 1.
// Define the Perlin class for generating Perlin noise.
class Perlin {
// Constructor initializes a new instance of the Perlin noise generator with a given seed.
constructor(seed) {
this.p = []; // Initialize permutation array.
let random = new SeededRandom(seed); // Create a seeded random generator for consistent shuffling.
let permutation = []; // Temporary array to hold the initial permutation of values.
for (let i = 0; i < 256; i++) {
permutation[i] = i; // Fill permutation array with values from 0 to 255.
}
// Shuffle the permutation array using the seeded random generator to ensure repeatability.
for (let i = 255; i > 0; i--) {
let j = Math.floor(random.nextFloat() * (i + 1));
// Swap the elements at indices i and j.
[permutation[i], permutation[j]] = [permutation[j], permutation[i]];
}
// Duplicate the shuffled permutation to avoid overflow when accessing elements.
this.p = permutation.concat(permutation);
}
// The fade function smoothens the transition between coordinate points.
fade(t) {
// Polynomial fade function for smoother transitions.
return t * t * t * (t * (t * 6 - 15) + 10);
}
// The lerp function performs linear interpolation between two points.
lerp(t, a, b) {
// Calculate the interpolated value.
return a + t * (b - a);
}
// Gradient function calculates a dot product based on a hashed value and the x, y, z coordinates.
// This contributes to the final noise value based on the spatial position.
grad(hash, x, y, z) {
const h = hash & 15; // Hash value constrained to 16 possibilities (0-15).
const u = h < 8 ? x : y; // Select x or y based on hash.
const v = h < 4 ? y : h === 12 || h === 14 ? x : z; // Select y or z based on hash.
return ((h & 1) === 0 ? u : -u) + ((h & 2) === 0 ? v : -v); // Calculate dot product based on hash.
}
// Generates Perlin noise for a given point in 3D space (x, y, z).
noise(x, y, z) {
// Find unit cube that contains the point and wrap the coordinates.
const X = Math.floor(x) & 255;
const Y = Math.floor(y) & 255;
const Z = Math.floor(z) & 255;
// Find relative x, y, z of the point in the cube.
x -= Math.floor(x);
y -= Math.floor(y);
z -= Math.floor(z);
// Compute fade curves for x, y, z.
const u = this.fade(x);
const v = this.fade(y);
const w = this.fade(z);
// Hash coordinates of the 8 cube corners.
const A = this.p[X] + Y;
const AA = this.p[A] + Z;
const AB = this.p[A + 1] + Z;
const B = this.p[X + 1] + Y;
const BA = this.p[B] + Z;
const BB = this.p[B + 1] + Z;
// Add blended results from 8 corners of the cube and interpolate the results.
return this.lerp(w, this.lerp(v, this.lerp(u, this.grad(this.p[AA], x, y, z), // Blend from the bottom front.
this.grad(this.p[BA], x - 1, y, z)), // to the bottom back.
this.lerp(u, this.grad(this.p[AB], x, y - 1, z), // Then blend from the top front.
this.grad(this.p[BB], x - 1, y - 1, z))), // to the top back.
this.lerp(v, this.lerp(u, this.grad(this.p[AA + 1], x, y, z - 1), // Repeat for the lower floor.
this.grad(this.p[BA + 1], x - 1, y, z - 1)),
this.lerp(u, this.grad(this.p[AB + 1], x, y - 1, z - 1), // And then for the upper floor.
this.grad(this.p[BB + 1], x - 1, y - 1, z - 1))));
}
}
// Define the Perlin class for generating Perlin noise.
public class Perlin
{
// Array to store the permutation table, which is essential for the noise generation algorithm.
private int[] permutationTable;
// Constant defining the size of the permutation table.
private const int tableSize = 256;
// Bitmask used for wrapping indices to table size, facilitating seamless tiling of noise.
private const int tableSizeMask = tableSize - 1;
// Instance of a seeded random number generator to shuffle the permutation table.
private SeededRandom seededRandom;
// Constructor that initializes the Perlin noise generator with a specific seed.
public Perlin(int seed)
{
seededRandom = new SeededRandom(seed);
permutationTable = new int[tableSize * 2];
// Temporary array to initialize a sequence of values.
int[] tempTable = new int[tableSize];
for (int i = 0; i < tableSize; i++)
tempTable[i] = i;
// Shuffle the temporary array with a Fisher-Yates shuffle, walking backwards and swapping each
// element with a random one at or before it. It's the same shuffle as the JavaScript version,
// so the same seed builds the same table (and the same world) in every language.
for (int i = tableSize - 1; i > 0; i--)
{
int j = (int)(seededRandom.NextFloat() * (i + 1));
// Swap elements at indices i and j.
int temp = tempTable[i];
tempTable[i] = tempTable[j];
tempTable[j] = temp;
}
// Duplicate the permutation table to avoid overflow when accessing indices.
for (int i = 0; i < tableSize; i++)
{
permutationTable[i] = tempTable[i];
permutationTable[tableSize + i] = tempTable[i];
}
}
// The Fade function smooths coordinate inputs to ease the transition between values.
private float Fade(float t)
{
// Uses Ken Perlin's fade function (6t^5 - 15t^4 + 10t^3) for smoothing.
return t * t * t * (t * (t * 6 - 15) + 10);
}
// Linearly interpolates between two values a and b using a blend factor t.
// t comes first, matching the calls in Noise() below (and the JavaScript version).
private float Lerp(float t, float a, float b)
{
// Simple linear interpolation.
return a + t * (b - a);
}
// Calculates a gradient vector from a hash value and adds contributions from x, y, and z.
private float Grad(int hash, float x, float y, float z)
{
// Calculate gradient vector based on hashed value.
int h = hash & 15;
float u = h < 8 ? x : y;
float v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
}
// Generates Perlin noise for a given point (x, y, z) in 3D space.
public float Noise(float x, float y, float z)
{
// Wrap the integer parts of x, y, and z to [0, 255] range.
int X = (int)Math.Floor(x) & tableSizeMask;
int Y = (int)Math.Floor(y) & tableSizeMask;
int Z = (int)Math.Floor(z) & tableSizeMask;
// Subtract the integer part to get fractional coordinates, which are used for interpolation.
x -= (int)Math.Floor(x);
y -= (int)Math.Floor(y);
z -= (int)Math.Floor(z);
// Calculate smooth fade curves for each of x, y, z.
float u = Fade(x);
float v = Fade(y);
float w = Fade(z);
// Hash coordinates of the cube corners and add blended results from the corners.
int A = permutationTable[X] + Y;
int AA = permutationTable[A] + Z;
int AB = permutationTable[A + 1] + Z;
int B = permutationTable[X + 1] + Y;
int BA = permutationTable[B] + Z;
int BB = permutationTable[B + 1] + Z;
// Blend the noise contributions from each of the eight cube corners.
float res = Lerp(w, Lerp(v, Lerp(u, Grad(permutationTable[AA], x, y, z), // The lower bound
Grad(permutationTable[BA], x - 1, y, z)), // The upper bound
Lerp(u, Grad(permutationTable[AB], x, y - 1, z), // The lower bound
Grad(permutationTable[BB], x - 1, y - 1, z))), // The upper bound
Lerp(v, Lerp(u, Grad(permutationTable[AA + 1], x, y, z - 1), // The lower bound
Grad(permutationTable[BA + 1], x - 1, y, z - 1)), // The upper bound
Lerp(u, Grad(permutationTable[AB + 1], x, y - 1, z - 1), // The lower bound
Grad(permutationTable[BB + 1], x - 1, y - 1, z - 1)))); // The upper bound
// The result is roughly between -1 and 1, the same range as the JavaScript version.
// (Unity's Mathf.PerlinNoise returns roughly 0 to 1 instead. If you need that, use (Noise(x, y, z) + 1) / 2.)
return res;
}
} // A class for generating Perlin noise, a procedural technique used in computer graphics to produce natural-looking textures.
class Perlin {
private:
// A table used for permutation in the Perlin noise algorithm. It's doubled to avoid overflow in indexing.
std::vector<int> permutationTable;
// The size of the permutation table.
static const int tableSize = 256;
// A bitmask used for wrapping indices to remain within the permutation table's bounds.
static const int tableSizeMask = tableSize - 1;
// Seeded random number generator to shuffle the permutation table in a reproducible way.
SeededRandom seededRandom;
// The Fade function smooths the input values to ease transitions, as described by Ken Perlin.
float Fade(float t) { return t * t * t * (t * (t * 6 - 15) + 10); }
// Linear interpolation between two values a and b using the blend factor t.
// t comes first, matching the calls in Noise() below (and the JavaScript version).
float Lerp(float t, float a, float b) { return a + t * (b - a); }
// Calculates a gradient based on a hash value and the x, y, z coordinates.
// This contributes to the pseudo-randomness of the noise.
float Grad(int hash, float x, float y, float z) {
int h = hash & 15;
float u = h < 8 ? x : y;
float v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
}
public:
// Constructor initializes the Perlin noise generator with a specific seed.
Perlin(int seed) : seededRandom(seed) {
permutationTable.resize(tableSize * 2);
std::vector<int> tempTable(tableSize);
for (int i = 0; i < tableSize; i++)
tempTable[i] = i;
// Shuffle the temporary table with a Fisher-Yates shuffle, walking backwards and swapping each
// element with a random one at or before it. It's the same shuffle as the JavaScript version,
// so the same seed builds the same table (and the same world) in every language.
for (int i = tableSize - 1; i > 0; i--) {
int j = static_cast<int>(seededRandom.NextFloat() * (i + 1));
std::swap(tempTable[i], tempTable[j]);
}
// Duplicate the shuffled permutation table to avoid overflow.
for (int i = 0; i < tableSize; i++) {
permutationTable[i] = tempTable[i];
permutationTable[tableSize + i] = tempTable[i];
}
}
// Generates Perlin noise for a given point (x, y, z) in 3D space.
float Noise(float x, float y, float z) {
// Find the unit cube containing the point and wrap the integer parts to the table size.
int X = static_cast<int>(std::floor(x)) & tableSizeMask;
int Y = static_cast<int>(std::floor(y)) & tableSizeMask;
int Z = static_cast<int>(std::floor(z)) & tableSizeMask;
// Calculate the relative position of the point in the cube.
x -= std::floor(x);
y -= std::floor(y);
z -= std::floor(z);
// Compute fade curves for x, y, z.
float u = Fade(x);
float v = Fade(y);
float w = Fade(z);
// Hash coordinates of the cube's eight corners.
int A = permutationTable[X] + Y;
int AA = permutationTable[A] + Z;
int AB = permutationTable[A + 1] + Z;
int B = permutationTable[X + 1] + Y;
int BA = permutationTable[B] + Z;
int BB = permutationTable[B + 1] + Z;
// Add blended results from the eight corners of the cube.
float res =
Lerp(w,
Lerp(v,
Lerp(u, Grad(permutationTable[AA], x, y, z),
Grad(permutationTable[BA], x - 1, y, z)),
Lerp(u, Grad(permutationTable[AB], x, y - 1, z),
Grad(permutationTable[BB], x - 1, y - 1, z))),
Lerp(v,
Lerp(u, Grad(permutationTable[AA + 1], x, y, z - 1),
Grad(permutationTable[BA + 1], x - 1, y, z - 1)),
Lerp(u, Grad(permutationTable[AB + 1], x, y - 1, z - 1),
Grad(permutationTable[BB + 1], x - 1, y - 1, z - 1))));
// The result is roughly between -1 and 1, the same range as the JavaScript version.
return res;
}
};
// Defines a class for generating Perlin noise, a procedural texture primitive, useful in computer graphics.
// Perlin noise is generated at any point in n-dimensional space, and it produces a smooth, natural-looking texture.
CLASS Perlin
// Constructor initializes a new instance of the Perlin class with a given seed for pseudo-randomness.
METHOD constructor(seed)
// Initialize an empty array for permutation table.
this.p = []
// Create an instance of the SeededRandom class with the provided seed for deterministic randomness.
DECLARE random = NEW SeededRandom(seed)
// Initialize a permutation array with values from 0 to 255, in order.
DECLARE permutation = ARRAY[0..255] INITIALLY EACH i = i
// Shuffle the permutation array using the seeded random generator to randomize the values without repetition.
FOR i FROM 255 DOWNTO 1
DECLARE j = FLOOR(random.nextFloat() * (i + 1)) // Calculate a random index to swap with.
SWAP permutation[i] WITH permutation[j] // Swap elements at indices i and j.
END FOR
// Duplicate the permutation array to avoid overflow when accessing it with indices beyond 255.
this.p = permutation + permutation
END METHOD
// Smoothens the input value t, enhancing the interpolation quality of the noise.
METHOD fade(t)
// Polynomial fade function improves the transition smoothness.
RETURN t^3 * (t * (t * 6 - 15) + 10)
END METHOD
// Linearly interpolates between two values, a and b, by a factor of t.
METHOD lerp(t, a, b)
// Computes the linear interpolation, which is essential for noise smoothness.
RETURN a + t * (b - a)
END METHOD
// Calculates gradient vectors and determines their influence on the specified coordinates.
METHOD grad(hash, x, y, z)
// Determine the gradient direction based on the hash value.
DECLARE h = hash AND 15
// Select the appropriate gradients based on the lower 4 bits of the hash.
DECLARE u = IF h < 8 THEN x ELSE y END IF
DECLARE v = IF h < 4 THEN y ELSE IF h == 12 OR h == 14 THEN x ELSE z END IF
// Compute the dot product of the gradient vector with the distance vector.
RETURN (IF h AND 1 == 0 THEN u ELSE -u END IF) + (IF h AND 2 == 0 THEN v ELSE -v END IF)
END METHOD
// Computes the Perlin noise value at a specific point in 3D space.
METHOD noise(x, y, z)
// Convert the floating-point coordinates to integers and apply bitwise AND to constrain them to 0-255 range.
DECLARE X = FLOOR(x) AND 255
DECLARE Y = FLOOR(y) AND 255
DECLARE Z = FLOOR(z) AND 255
// Fractional part of the coordinates for interpolation.
x -= FLOOR(x)
y -= FLOOR(y)
z -= FLOOR(z)
// Apply fade function to each coordinate to smooth transitions.
DECLARE u = this.fade(x)
DECLARE v = this.fade(y)
DECLARE w = this.fade(z)
// Hash coordinates of the 8 cube corners and add offsets.
DECLARE A = this.p[X] + Y
DECLARE AA = this.p[A] + Z
DECLARE AB = this.p[A + 1] + Z
DECLARE B = this.p[X + 1] + Y
DECLARE BA = this.p[B] + Z
DECLARE BB = this.p[B + 1] + Z
// Interpolate between the gradients at the corners of the cube that contains the input point.
// This interpolation gives the final noise value, which is smooth and appears more natural.
RETURN this.lerp(w, this.lerp(v, this.lerp(u, this.grad(this.p[AA], x, y, z),
this.grad(this.p[BA], x - 1, y, z)),
this.lerp(u, this.grad(this.p[AB], x, y - 1, z),
this.grad(this.p[BB], x - 1, y - 1, z))),
this.lerp(v, this.lerp(u, this.grad(this.p[AA + 1], x, y, z - 1),
this.grad(this.p[BA + 1], x - 1, y, z - 1)),
this.lerp(u, this.grad(this.p[AB + 1], x, y - 1, z - 1),
this.grad(this.p[BB + 1], x - 1, y - 1, z - 1))))
END METHOD
END CLASS
How Perlin Noise Works, One Cell at a Time
Our class is 3D, but at z = 0 it behaves exactly like 2D Perlin noise, which is easier to see. The lab below draws the noise field with every corner’s gradient arrow, taken straight from the class’s own grad(). Drag the white dot and watch the four dot products and the final blend update. The last number is checked against a real call to noise().
Lab: Inside a Perlin Cell
grad() picks from the permutation table; the dashed line is the offset from that corner to the dot.👉 Try this: drag the dot right onto a grid corner. The offset to that corner shrinks to (0, 0), so its dot product is 0, and the blend gives that corner all the weight. Perlin noise is 0 at every whole-number coordinate, which is the first pitfall at the end of this tutorial. Then tick Show the zero line: the white contour passes through every single grid corner, because that’s where the noise is always 0.
The Fade Curve
Untick Use fade() in the lab above and the dot’s value changes, even though the corners and dot products don’t. The fade curve only changes how the four proposals are blended. Ken Perlin’s 1985 noise used the smoothstep curve 3t² − 2t³. In 2002, his paper “Improving Noise” switched to 6t⁵ − 15t⁴ + 10t³, because the old curve’s second derivative jumps at every cell edge, and that showed up as grid artifacts when noise was used for bump maps and lighting.
Lab: The Fade Curve
👉 Try this: start on Linear with the lit view. Every grid line shows up as a crease where the light catches it. Smoothstep fixes the creases, so it looks right when lit. Now pick Curvature in the View menu: smoothstep still has seams along every grid line, and Perlin’s fade has none. That’s the bug the 2002 paper fixed.
Step 3: Sample Perlin Noise at a Point
Create a Perlin with a seed and ask for a value at any point. Notice the coordinates: 0.5, 0.5 is the middle of the first cell. Asking for noise(1, 2, 0) would return exactly 0, because that’s a grid corner.
const seed = 123456; // Example seed
const perlin = new Perlin(seed);
const noiseValue = perlin.noise(0.5, 0.5, 0);
console.log("Noise Value: "+noiseValue); // Prints -0.125 class Program
{
public static void Main(string[] args)
{
// Initialize the Perlin instance with a seed
int seed = 123456; // Example seed
Perlin perlin = new Perlin(seed);
// Define parameters for the Noise call
float x = 0.5f; // Example X coordinate
float y = 0.5f; // Example Y coordinate
float z = 0.0f; // Example Z coordinate (can be 0 for 2D noise)
// Call the Noise method and print the result
float noiseValue = perlin.Noise(x, y, z);
Console.WriteLine($"Noise Value: {noiseValue}"); // Prints -0.125
}
} int main() {
int seed = 123456;
Perlin perlin(seed);
float x = 0.5f;
float y = 0.5f;
float z = 0.0f;
float noiseValue =
perlin.Noise(x, y, z);
std::cout << "Noise Value: " << noiseValue << std::endl; // Prints -0.125
return 0;
} DECLARE seed = 123456
// Create a new Perlin noise object
DECLARE perlin = NEW Perlin(seed)
// Generate a noise value using the Perlin noise object with coordinates (0.5, 0.5, 0)
DECLARE noiseValue = perlin.noise(0.5, 0.5, 0)
// Print the generated noise value (-0.125 with this seed)
PRINT noiseValue
Step-by-Step Lab #2: Fractal Perlin Noise with Octaves
One layer of Perlin noise gives you soft, round blobs: fine for clouds, too smooth for a coastline. Real landscapes have detail at every scale. A continent has bays, the bays have coves, the coves have rocks. Fractal noise (also called fractional Brownian motion, or fBm) fakes that by stacking several layers of noise, called octaves. Each octave has a higher frequency, so smaller features, and a lower amplitude, so a gentler effect.
Step 1: Add the fractalNoise Method
fractalNoise() loops over the octaves. Each pass samples noise() at a higher frequency, scales it by a smaller amplitude and adds it to the total. At the end it divides by the sum of all the amplitudes, so the result stays in the same −1 to 1 range however many octaves you use. Each octave also shifts its coordinates by i * 2, so the layers don’t all line up on the same grid corners.
class Perlin {
// ...constructor, fade(), lerp(), grad() and noise() from the previous step stay here...
/**
* Generates fractal noise by layering multiple octaves of Perlin noise.
* Each octave contributes to the final noise with its own frequency and amplitude,
* creating a more complex and natural-looking pattern.
*
* @param {number} x - The x coordinate in 3D space.
* @param {number} y - The y coordinate in 3D space.
* @param {number} z - The z coordinate in 3D space, kept constant for 2D noise.
* @param {number} octaves - The number of layers of noise to generate.
* @param {number} persistence - Determines how the amplitude of octaves decreases.
* @param {number} lacunarity - Determines how the frequency of octaves increases.
* @returns {number} A single floating-point value representing the generated noise at the given coordinates.
*/
fractalNoise(x, y, z, octaves = 4, persistence = 0.5, lacunarity = 2.0) {
let total = 0; // Accumulates the total noise value.
let frequency = 1; // The starting frequency of the first octave.
let amplitude = 1; // The starting amplitude of the first octave.
let maxValue = 0; // The largest total possible, used to scale the result back into noise()'s -1 to 1 range.
for (let i = 0; i < octaves; i++) {
// Offset the coordinates for each octave to introduce variation.
let xOffset = i * 2;
let yOffset = i * 2;
// Calculate the noise value for this octave and add it to the total, adjusted by its frequency and amplitude.
total += this.noise((x + xOffset) * frequency, (y + yOffset) * frequency, z) * amplitude;
// Accumulate the maximum possible value for normalization purposes.
maxValue += amplitude;
// Adjust the amplitude and frequency for the next octave according to the persistence and lacunarity.
amplitude *= persistence; // Persistence decreases amplitude with each octave, making higher octaves contribute less.
frequency *= lacunarity; // Lacunarity increases frequency with each octave, adding more detail with each layer.
}
// Divide by maxValue so the result stays in the same -1 to 1 range as noise(), however many octaves you add.
return total / maxValue;
}
}
public class Perlin
{
// ...constructor, Fade(), Lerp(), Grad() and Noise() from the previous step stay here...
/// <summary>
/// Generates fractal noise by layering multiple octaves of Perlin noise. This method enhances the visual complexity
/// and natural appearance of the noise, making it suitable for generating more detailed and varied textures or terrains.
/// </summary>
/// <param name="x">The x coordinate in the noise space.</param>
/// <param name="y">The y coordinate in the noise space.</param>
/// <param name="z">The z coordinate in the noise space. For 2D noise, this can be kept constant.</param>
/// <param name="octaves">The number of iterations of noise to layer. More octaves create more detail, at the cost of performance.</param>
/// <param name="persistence">Controls the decrease in amplitude of each octave. Lower values make the noise smoother.</param>
/// <param name="lacunarity">Controls the increase in frequency of each octave. Higher values create more detailed noise patterns.</param>
/// <returns>A single float value representing the generated fractal noise, in the same -1 to 1 range as Noise().</returns>
public float FractalNoise(float x, float y, float z, int octaves = 4, float persistence = 0.5f, float lacunarity = 2.0f)
{
float total = 0; // Total noise accumulated across all octaves.
float frequency = 1; // Initial frequency of the noise.
float amplitude = 1; // Initial amplitude of the noise.
float maxValue = 0; // Accumulator to track the maximum possible value for normalization.
// Loop through each octave, applying and accumulating Perlin noise based on current amplitude and frequency.
for (int i = 0; i < octaves; i++)
{
// Calculate an offset to ensure each octave samples a different part of the noise space.
int offset = i * 2;
// Accumulate noise value, scaled by amplitude, and adjust frequency and amplitude for the next octave.
total += Noise((x + offset) * frequency, (y + offset) * frequency, z) * amplitude;
// Accumulate the max possible value to use for normalization later.
maxValue += amplitude;
// Adjust amplitude by persistence (reduces each octave's influence) and frequency by lacunarity (increases detail).
amplitude *= persistence;
frequency *= lacunarity;
}
// Divide by maxValue so the result stays in the same -1 to 1 range as Noise().
return total / maxValue;
}
}
class Perlin
{
// ...constructor, Fade(), Lerp(), Grad() and Noise() from the previous step stay here...
public:
/// Generates fractal noise by combining multiple octaves of Perlin noise.
/// Each octave contributes to the final noise output with its own frequency and amplitude,
/// creating a more complex and visually interesting result. This method is especially useful
/// for generating realistic textures or terrain in game development.
///
/// @param x The x coordinate in the noise space.
/// @param y The y coordinate in the noise space.
/// @param z The z coordinate in the noise space, useful for 3D noise but can be kept constant for 2D.
/// @param octaves The number of iterations or layers of noise to combine for the final output.
/// More octaves lead to more detail at the cost of computation time.
/// @param persistence Determines how much each subsequent octave contributes to the total noise.
/// A lower persistence value makes the noise smoother.
/// @param lacunarity Controls the frequency growth for each octave. Higher lacunarity values
/// increase the complexity of the noise pattern.
/// @return A single float value representing the fractal noise at the given coordinates,
/// in the same -1 to 1 range as Noise().
float FractalNoise(float x, float y, float z, int octaves = 4, float persistence = 0.5f,
float lacunarity = 2.0f) {
float total = 0; // Accumulates the total noise value from all octaves.
float frequency = 1; // The starting frequency of the noise.
float amplitude = 1; // The starting amplitude of the noise.
float maxValue = 0; // The largest total possible, used to scale the result back into Noise()'s -1 to 1 range.
// Iterate through each octave to layer the noise.
for (int i = 0; i < octaves; i++) {
int offset = i * 2; // Apply an offset to each octave to vary the noise pattern.
// Add the noise value, scaled by the current amplitude and frequency, to the total.
total += Noise((x + offset) * frequency, (y + offset) * frequency, z) * amplitude;
// Accumulate the maximum possible value to normalize the result later.
maxValue += amplitude;
// Decrease the amplitude by the persistence factor for each subsequent octave.
amplitude *= persistence;
// Increase the frequency by the lacunarity factor for each subsequent octave.
frequency *= lacunarity;
}
// Divide by maxValue so the result stays in the same -1 to 1 range as Noise().
return total / maxValue;
}
};
CLASS Perlin
// ...constructor, fade, lerp, grad and noise METHODs from the previous step stay here...
// Method to generate fractal noise, which enhances basic Perlin noise by layering multiple octaves of noise.
// This method results in noise that appears more complex and natural, suitable for textures, terrain, and other procedural content.
METHOD fractalNoise(x, y, z, octaves = 4, persistence = 0.5, lacunarity = 2.0)
// Initialize total to accumulate noise values across all octaves.
DECLARE total = 0
// Starting frequency for the first octave.
DECLARE frequency = 1
// Starting amplitude for the first octave.
DECLARE amplitude = 1
// The largest total possible, used to scale the result back into noise's -1 to 1 range. This keeps the final
// value in a predictable range however many octaves you add, making it easier to use in applications.
DECLARE maxValue = 0
// Iterate over each octave, adding layered noise values.
FOR i FROM 0 TO octaves - 1
// Calculate an offset for each octave to ensure varied and interesting results.
// This offset helps in avoiding repetitive patterns in the generated noise.
DECLARE offset = i * 2
// Accumulate the noise value, adjusted by the current frequency and amplitude, into the total.
// The use of an offset here helps in ensuring that each octave contributes unique characteristics to the overall noise.
total += this.noise((x + offset) * frequency, (y + offset) * frequency, z) * amplitude
// Accumulate the maximum possible value to use for normalization later.
maxValue += amplitude
// Adjust amplitude by the persistence for the next octave. Persistence controls the decrease in amplitude
// with each octave, affecting the "roughness" of the noise. Lower persistence values produce smoother noise.
amplitude *= persistence
// Adjust frequency by the lacunarity for the next octave. Lacunarity controls the frequency increase
// with each octave, affecting the detail of the noise. Higher lacunarity values produce more detailed noise.
frequency *= lacunarity
END FOR
// Divide by maxValue so the result stays in the same -1 to 1 range as noise().
// This normalization step is crucial for ensuring the output is consistently scaled across different inputs and noise configurations.
RETURN total / maxValue
END METHOD
END CLASS
Lab: Stack the Octaves
fractalNoise() itself: the layers added up and divided by the total amplitude. 👉 Try this: set Octaves to 1 for plain Perlin noise, then add them one at a time and watch the coral sum line roughen. Drag Persistence to 0.8: the small octaves stay loud and the map turns to gravel. Drop it to 0.3 and the detail almost vanishes. Then push Lacunarity to 3 and look at the table: by octave 6, the frequency is 243 times the first.
Key Parameters
- x, y, z: where you sample. For a 2D map, use x and y and keep z fixed; move z slowly to morph the map over time.
- Octaves: how many layers to add. Each one costs another
noise()call per sample, so 8 octaves are 8 times the work of 1. Four to six is plenty for most terrain. - Persistence: how much quieter each octave gets. At 0.5, each layer has half the amplitude of the one before. Higher values make rougher, noisier terrain; lower values make smooth, rolling hills.
- Lacunarity: how much faster each octave changes. The usual choice is 2, which doubles the frequency every layer. Above about 2.5, the octaves stop blending and the layers start to look separate.
- Frequency: how big the features are, set by how you scale the coordinates before you call the function (
x * 0.03, for example). Smaller numbers zoom in to big, sweeping shapes.
A low octave count with high persistence gives gently rolling hills. More octaves with low persistence and a high lacunarity look more like rugged mountains.
Step 2: Call fractalNoise
const seed = 123456; // Example seed
const octaves = 4;
const persistence = 0.5;
const lacunarity = 2.0;
const x = 1.3;
const y = 2.7;
const z = 0.0;
const perlin = new Perlin(seed);
const noiseValue = perlin.fractalNoise(x, y, z, octaves, persistence, lacunarity);
console.log("Noise Value: "+noiseValue); // Prints about 0.1441 class Program
{
public static void Main(string[] args)
{
// Initialize the Perlin instance with a seed
int seed = 123456; // Example seed
Perlin perlin = new Perlin(seed);
// Define parameters for the FractalNoise call
float x = 1.3f; // Example X coordinate
float y = 2.7f; // Example Y coordinate
float z = 0.0f; // Example Z coordinate (can be 0 for 2D noise)
int octaves = 4;
float persistence = 0.5f;
float lacunarity = 2.0f; // Example lacunarity value
// Call the FractalNoise method and print the result
float noiseValue = perlin.FractalNoise(x, y, z, octaves, persistence, lacunarity);
Console.WriteLine($"Fractal Noise Value: {noiseValue}"); // Prints about 0.1441
}
} int main() {
int seed = 123456;
Perlin perlin(seed);
float x = 1.3f;
float y = 2.7f;
float z = 0.0f;
int octaves = 4;
float persistence = 0.5f;
float lacunarity = 2.0f;
float noiseValue =
perlin.FractalNoise(x, y, z, octaves, persistence, lacunarity);
std::cout << "Fractal Noise Value: " << noiseValue << std::endl; // Prints about 0.1441
return 0;
} DECLARE seed = 123456
DECLARE octaves = 4
DECLARE persistence = 0.5
DECLARE lacunarity = 2.0
DECLARE x = 1.3
DECLARE y = 2.7
DECLARE z = 0.0
// Create a new Perlin noise object
DECLARE perlin = NEW Perlin(seed)
DECLARE noiseValue = perlin.fractalNoise(x, y, z, octaves, persistence, lacunarity)
// Print the generated noise value (about 0.1441 with this seed)
PRINT noiseValue
Step-by-Step Lab #3: Use Perlin Noise in 1D and 2D
Noise gives you numbers between −1 and 1. To use them in a game, you turn each number into something you can see or feel: a position, a size, a brightness, a height. Read the noise along a line, one step per frame, and you get smooth motion: a torch that flickers, a camera that shakes, a cloud that drifts. Read it across a grid and you get an image, which is how you’d use it for terrain or a texture. We’ll draw both, then watch them drive a game effect.
Step 1: Set Up the Page
Two canvases and two scripts: perlin.js holds SeededRandom and Perlin, and visualize.js holds the drawing code from the next two steps.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Perlin Noise</title>
</head>
<body>
<canvas id="canvas1D" width="800" height="150"></canvas>
<canvas id="canvas2D" width="400" height="400"></canvas>
<!-- perlin.js holds SeededRandom and Perlin; visualize.js holds the drawing code below. -->
<script src="perlin.js"></script>
<script src="visualize.js"></script>
</body>
</html> Step 2: Draw a 1D Line
visualize1D() walks across the canvas one pixel at a time, samples fractalNoise() at i * xIncrement and turns the −1 to 1 result into a height on the canvas.
function visualize1D(perlin, octaves, persistence, lacunarity, xIncrement) {
const canvas = document.getElementById('canvas1D');
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
ctx.clearRect(0, 0, width, height);
ctx.beginPath();
ctx.strokeStyle = '#FF6F61'; // Set the line color
for (let i = 0; i < width; i++) {
const noiseVal = perlin.fractalNoise(i * xIncrement, 0, 0, octaves, persistence, lacunarity);
const y = height - (noiseVal + 1) * height / 2; // Scale noise to canvas height
if (i === 0) ctx.moveTo(i, y);
else ctx.lineTo(i, y);
}
ctx.stroke();
}
// Draw once the page has loaded. Using addEventListener (instead of window.onload = ...) means
// the 1D, 2D and height map examples can all run on the same page without replacing each other.
window.addEventListener('load', function() {
const seed = 777;
const octaves = 4; //Between 1-8
const persistence = .5; //Between 0-1
const lacunarity = 2.0; //Between 1.0-3.0
const xIncrement = .03; //Increment scales the noise - Between .01-.2
// Initialize Perlin noise with the new seed
const perlin = new Perlin(seed);
visualize1D(perlin, octaves, persistence, lacunarity, xIncrement);
}); Step 3: Draw a 2D Image
visualize2D() does the same thing for every pixel, then maps −1 to black and 1 to white.
function visualize2D(perlin, octaves, persistence, lacunarity, xIncrement, yIncrement) {
const canvas = document.getElementById('canvas2D');
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
const imageData = ctx.createImageData(width, height);
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const noiseVal = perlin.fractalNoise(x * xIncrement, y * yIncrement, 0, octaves, persistence, lacunarity);
const color = Math.floor((noiseVal + 1) * 128);
const index = (x + y * width) * 4;
imageData.data[index] = imageData.data[index + 1] = imageData.data[index + 2] = color;
imageData.data[index + 3] = 255; // Alpha channel
}
}
ctx.putImageData(imageData, 0, 0);
}
// Draw once the page has loaded (addEventListener lets this run alongside the 1D example).
window.addEventListener('load', function() {
const seed = 777;
const octaves = 4; //Between 1-8
const persistence = .5; //Between 0-1
const lacunarity = 2.0; //Between 1.0-3.0
const xIncrement = .03; //Increment scales the noise - Between .01-.2
const yIncrement = .03; //Increment scales the noise - Between .01-.2
// Initialize Perlin noise with the new seed
const perlin = new Perlin(seed);
visualize2D(perlin, octaves, persistence, lacunarity, xIncrement, yIncrement);
}); Lab: Noise in Motion
visualize1D(): the noise the torch reads, left to rightMath.random() - 0.5, a new value at each whole step of x2D: every pixel is one value
visualize1D() and visualize2D() exactly as printed above (4 octaves, persistence 0.5, lacunarity 2). The marker moves one pixel per frame, so Increment sets how far through the noise each frame steps: the speed of the motion. The random torch gets a new number each time x passes a whole number, the same spacing as the noise's grid, so both speed up together. Camera shake reads a second line of the same noise (y = 10) for its vertical wobble.👉 Try this: watch the two torches for a few seconds. The Perlin flame breathes, while the random one snaps from one size to the next, because each random number has nothing to do with the one before it. Switch to Camera shake and you’ll feel the same difference: a smooth sway against a jolt. Then drag Increment from 0.02 up to 0.25. Both torches speed up, and now the Perlin flame twitches too: each frame jumps so far along the noise that neighboring values stop being related. Small steps give smooth motion; big steps give static.
In your own game, that’s one line per frame: flameSize = 1 + 0.9 * perlin.fractalNoise(time * speed, 0, 0). Use a second line of noise (a different y) for anything that needs its own wobble, like the vertical half of a camera shake.
In the image, point at any pixel to see how its value becomes a shade of gray: −1 is black, 0 is mid-gray and 1 is white. Lab #4 uses exactly the same idea, but swaps the grays for terrain colors.
Step-by-Step Lab #4: Turn Perlin Noise into a Terrain Height Map
A height map is a grid of numbers where each one is the ground’s height at that spot. Fractal noise makes a great one: low values become oceans, high values become mountains. We’ll build it in three steps: generate the numbers, add a canvas, then color them.
Step 1: Generate the Height Map
generateHeightMap() fills a 2D array with fractalNoise() values. It first converts each pixel to the 0 to 1 range (nx, ny), so the map covers the same patch of noise whatever its size in pixels. Then it adds the offsets and scales by the increment. xOffset and yOffset scroll the map across the noise, and zOffset slices it at a different depth, which morphs the terrain.
// Generates a height map using fractal noise based on Perlin noise.
// This method is particularly useful for simulating realistic terrain in computer graphics.
// xOffset and yOffset scroll the map across the noise, and zOffset picks a different 2D slice of it,
// which morphs the terrain smoothly. That's what dragging the map and the Z slider in the terrain lab do.
function generateHeightMap(width, height, xOffset, yOffset, zOffset, seed, octaves = 4, persistence = 0.5, lacunarity = 2.0, xIncrement = .03, yIncrement = .03) {
// Instantiate the Perlin class with the given seed to generate consistent noise patterns.
const perlin = new Perlin(seed);
// Initialize the height map array with the specified height.
let map = new Array(height);
// Iterate over each row of the map.
for (let y = 0; y < height; y++) {
// Initialize each row with an array of the specified width.
map[y] = new Array(width);
for (let x = 0; x < width; x++) {
// Convert x and y to the 0..1 range, so the map covers the same patch of noise whatever its size in pixels.
const nx = x / width, ny = y / height;
// Generate fractal noise for each point on the map using the normalized coordinates plus the offsets.
// (xIncrement * 100) sets how many noise cells the map spans: 0.03 gives 3 cells across,
// and bigger values zoom out to show more, smaller features.
map[y][x] = perlin.fractalNoise((nx + xOffset) * (xIncrement * 100), (ny + yOffset) * (yIncrement * 100), zOffset, octaves, persistence, lacunarity);
}
}
// Return the populated height map array, where each value represents the elevation at that point.
return map;
}
// Defines a class responsible for generating height maps using Perlin noise.
// Height maps are two-dimensional arrays where each value represents the height at that point,
// which is useful for terrain generation in game development.
public class HeightMapGenerator
{
// Holds an instance of the Perlin class, which is used to generate the noise values.
private Perlin perlin;
// Constructor that initializes the HeightMapGenerator with a specific seed for the Perlin noise.
// This seed ensures that the generated noise (and thus the terrain) is reproducible.
public HeightMapGenerator(int seed)
{
this.perlin = new Perlin(seed);
}
// Generates a height map based on Perlin noise with specified parameters.
// Parameters allow customization of the noise to achieve different visual effects.
// xOffset and yOffset scroll the map across the noise, and zOffset picks a different 2D slice of it,
// which morphs the terrain smoothly (the same parameters as the JavaScript and C++ versions).
public float[,] GenerateHeightMap(int width, int height, float xOffset, float yOffset, float zOffset, int octaves = 4, float persistence = 0.5f, float lacunarity = 2.0f, float xIncrement = 0.03f, float yIncrement = 0.03f)
{
// Initialize the height map array with dimensions specified by width and height.
float[,] map = new float[height, width];
// Iterate over each cell in the map array to calculate its height.
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// Normalize x and y coordinates to a range of [0, 1] to ensure that
// the noise function works uniformly across the height map.
float nx = x / (float)width, ny = y / (float)height;
// Calculate the height value using fractal noise, which combines multiple
// octaves of Perlin noise for more complex patterns. The offsets move the map
// across the noise, and xIncrement and yIncrement scale the coordinates to adjust
// the frequency of the noise: 0.03 gives 3 noise cells across the map.
map[y, x] = perlin.FractalNoise((nx + xOffset) * (xIncrement * 100), (ny + yOffset) * (yIncrement * 100), zOffset, octaves, persistence, lacunarity);
}
}
// Return the populated height map, with each value representing the elevation at that point.
return map;
}
}
// A function that generates a 2D height map using Perlin noise.
// The height map is represented as a 2D vector of floats, where each float represents the height at that coordinate.
std::vector<std::vector<float>> generateHeightMap(
int width, // The width of the height map in units.
int height, // The height of the height map in units.
float xOffset, // Horizontal offset to apply to the noise function, allows for shifting the noise horizontally.
float yOffset, // Vertical offset to apply to the noise function, allows for shifting the noise vertically.
float zOffset, // Offset in the z-axis for the noise function, useful for generating different slices of 3D noise.
int perlinSeed, // Seed value for the Perlin noise generator, ensures reproducible results.
int octaves = 4, // Number of noise layers to combine, affects the complexity of the noise.
float persistence = 0.5f, // Controls the amplitude decrease for each octave, affecting the "roughness" of the terrain.
float lacunarity = 2.0f, // Controls the frequency increase for each octave, affecting the detail of the terrain.
float xIncrement = 0.03f, // Scale factor for the x-coordinate, controls the horizontal scale of the noise patterns.
float yIncrement = 0.03f // Scale factor for the y-coordinate, controls the vertical scale of the noise patterns.
) {
// Initialize the Perlin object with the given seed.
Perlin perlin(perlinSeed);
// Create a 2D vector to hold the height values of the map.
std::vector<std::vector<float>> map(height, std::vector<float>(width));
// Iterate over every cell in the map to calculate its height.
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// Normalize the current coordinates to a range of [0, 1] to ensure consistent noise scaling.
float nx = static_cast<float>(x) / static_cast<float>(width);
float ny = static_cast<float>(y) / static_cast<float>(height);
// Generate fractal noise for the current point using the normalized coordinates,
// adjusted by the provided offsets and scale factors. This noise value represents
// the height at this point on the map.
map[y][x] = perlin.FractalNoise(
(nx + xOffset) * (xIncrement * 100),
(ny + yOffset) * (yIncrement * 100),
zOffset, octaves, persistence, lacunarity
);
}
}
// Return the populated height map.
return map;
}
// Initializes variables for the dimensions of the height map, offsets in each dimension, and parameters for noise generation.
DECLARE width, height, xOffset, yOffset, zOffset, perlinSeed, octaves = 4, persistence = 0.5, lacunarity = 2.0, xIncrement = 0.03, yIncrement = 0.03
// Create an instance of the Perlin class with the provided seed to generate consistent, pseudo-random noise.
DECLARE perlin = NEW Perlin(perlinSeed)
// Initialize an empty array to store the height map data.
DECLARE map = NEW Array(height)
// Loop through each cell in the height map array to calculate its height based on Perlin noise.
FOR y FROM 0 TO height - 1 DO
// Initialize the current row in the map.
map[y] = NEW Array(width)
FOR x FROM 0 TO width - 1 DO
// Convert x and y to the 0..1 range, so the map covers the same patch of noise whatever its size in pixels.
DECLARE nx = x / width
DECLARE ny = y / height
// Apply offsets and increments to the normalized coordinates to control the "look" and "scale" of the terrain.
// The offsets allow for scrolling through the noise space, while the increments adjust the frequency of the noise.
// Generating fractal noise using the adjusted coordinates and the specified noise parameters.
// This combines multiple layers of Perlin noise to create a more complex and natural-looking height map.
map[y][x] = perlin.fractalNoise((nx + xOffset) * (xIncrement * 100), (ny + yOffset) * (yIncrement * 100), zOffset, octaves, persistence, lacunarity)
END FOR
END FOR
// Return the fully populated height map, now containing the generated terrain heights.
RETURN map
Step 2: Add a Canvas
<canvas id="terrainCanvas" width="600" height="400"></canvas> Step 3: Color the Heights
getColorForHeight() turns each height into a terrain color with a ladder of thresholds: deep ocean below −0.45, then ocean, shallow water, beach, grassland, forest, mountains, and snow above 0.45. visualizeHeightMap() paints one pixel per value.
function visualizeHeightMap(map, canvasId) {
const canvas = document.getElementById(canvasId);
if (!canvas) return;
const ctx = canvas.getContext('2d');
const width = map[0].length;
const height = map.length;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const value = map[y][x];
ctx.fillStyle = getColorForHeight(value);
ctx.fillRect(x, y, 1, 1); // Drawing a 1x1 pixel rectangle for each point
}
}
}
function getColorForHeight(value) {
if (value < -0.45) return '#204D75'; // Deep Ocean
else if (value < -0.25) return '#367ABD'; // Ocean
else if (value < -0.1) return '#76A5AF'; // Shallow Water
else if (value < 0) return '#C2B280'; // Beach
else if (value < 0.2) return '#8DB255'; // Grassland
else if (value < 0.3) return '#228B22'; // Forest Green
else if (value < 0.45) return '#7E5E60'; // Mountain Range
else return '#FFF8F0'; // Snow Peaks
}
// Draw once the page has loaded (addEventListener lets this run alongside the earlier examples).
window.addEventListener('load', function() {
const seed = 777;
const octaves = 4; //Between 1-8
const persistence = .5; //Between 0-1
const lacunarity = 2.0; //Between 1.0-3.0
const xIncrement = .03; //Increment scales the noise - Between .01-.2
const yIncrement = .03; //Increment scales the noise - Between .01-.2
const xOffset = 0, yOffset = 0, zOffset = 0; // Try changing these to scroll and morph the terrain
const map = generateHeightMap(600, 400, xOffset, yOffset, zOffset, seed, octaves, persistence, lacunarity, xIncrement, yIncrement);
visualizeHeightMap(map, 'terrainCanvas');
}); Lab: Terrain Height Map
xOffset and yOffset; the Z slider is zOffset. 👉 Try this: drag the map. You’re changing xOffset and yOffset, and new land keeps appearing in every direction, the same every time for this seed. Move Z slowly and the coastlines melt into new shapes. Then try Persistence 0.7 with Octaves 8 for a craggy archipelago, and compare the water percentage with the defaults.
You can tune the colors too. Move the thresholds in getColorForHeight() and the world gets wetter, drier or snowier without touching the noise.
Step-by-Step Lab #5: Shape the Noise
Plain fractal noise makes nice hills, but every map looks a bit like every other map. The fix is to reshape the numbers after you sample them, or to change where you sample. Four small functions cover a lot of ground:
terrace()snaps heights to flat steps, for mesas, rice terraces or blocky voxel layers.ridged()folds the noise at zero with an absolute value and flips it, so the old coastlines become sharp mountain crests.islandMask()lifts the middle of the map and sinks the edges, so any seed becomes an island surrounded by sea.warpedNoise()is domain warping: it nudges the sample point by two extra noise lookups first, which bends round blobs into fjords and swirls.
Step 1: Add the Shaping Functions
/*
Step 1: Shape the noise
-----------------------
fractalNoise() gives rolling hills everywhere. These four helpers reshape a height
value (or the coordinates you sample at) so the same noise turns into terraces,
mountain ridges, an island or twisting coastlines.
*/
// Snap heights to flat steps, like rice terraces or a voxel game's layers.
function terrace(value, steps = 6) {
// Round to the nearest step: with 6 steps, heights become ..., -1/6, 0, 1/6, ...
return Math.floor(value * steps + 0.5) / steps;
}
// Fold the noise at zero, then flip it, so the old coastline (value 0) becomes a sharp crest.
function ridged(value) {
return 0.5 - 2 * Math.abs(value); // Crest at 0.5 (snow), valleys fall away on both sides.
}
// Raise the middle of the map and sink the edges, so the land becomes an island.
// nx and ny are the point's position on the map, from 0 to 1.
function islandMask(value, nx, ny, falloff = 1.1) {
const dx = nx * 2 - 1; // -1 at the left edge, 0 in the middle, 1 at the right edge.
const dy = ny * 2 - 1;
const d = Math.min(1, Math.sqrt(dx * dx + dy * dy)); // Distance from the center, capped at 1.
return value + 0.35 - falloff * d * d; // Lift the center a little, push the edges under water.
}
// Domain warping: nudge the sample point by two more noise lookups before sampling.
// The pattern bends into fjords and swirls instead of round blobs.
function warpedNoise(perlin, x, y, z, strength = 1.5) {
const qx = perlin.fractalNoise(x + 5.2, y + 1.3, z); // Offsets pick unrelated parts of the noise,
const qy = perlin.fractalNoise(x + 1.7, y + 9.2, z); // so the x and y nudges don't move together.
return perlin.fractalNoise(x + strength * qx, y + strength * qy, z);
}
/*
Explanation:
- Each helper takes the -1..1 heights from fractalNoise() and returns heights in about the
same range, so getColorForHeight() still works on the result.
- They chain: terrace(islandMask(value, nx, ny)) gives a terraced island.
- warpedNoise() calls fractalNoise() three times, so it costs three times as much.
Next step: feed the shaped heights to visualizeHeightMap() and compare them in the lab.
*/
using System;
// Step 1: Shape the noise
// -----------------------
// FractalNoise() gives rolling hills everywhere. These four helpers reshape a height
// value (or the coordinates you sample at) so the same noise turns into terraces,
// mountain ridges, an island or twisting coastlines.
public static class NoiseShapes
{
// Snap heights to flat steps, like rice terraces or a voxel game's layers.
public static float Terrace(float value, int steps = 6)
{
// Round to the nearest step: with 6 steps, heights become ..., -1/6, 0, 1/6, ...
// (Math.Floor(v + 0.5) rounds the same way as the JavaScript version; Math.Round wouldn't.)
return (float)Math.Floor(value * steps + 0.5f) / steps;
}
// Fold the noise at zero, then flip it, so the old coastline (value 0) becomes a sharp crest.
public static float Ridged(float value)
{
return 0.5f - 2 * Math.Abs(value); // Crest at 0.5 (snow), valleys fall away on both sides.
}
// Raise the middle of the map and sink the edges, so the land becomes an island.
// nx and ny are the point's position on the map, from 0 to 1.
public static float IslandMask(float value, float nx, float ny, float falloff = 1.1f)
{
float dx = nx * 2 - 1; // -1 at the left edge, 0 in the middle, 1 at the right edge.
float dy = ny * 2 - 1;
float d = Math.Min(1f, (float)Math.Sqrt(dx * dx + dy * dy)); // Distance from the center, capped at 1.
return value + 0.35f - falloff * d * d; // Lift the center a little, push the edges under water.
}
// Domain warping: nudge the sample point by two more noise lookups before sampling.
// The pattern bends into fjords and swirls instead of round blobs.
public static float WarpedNoise(Perlin perlin, float x, float y, float z, float strength = 1.5f)
{
float qx = perlin.FractalNoise(x + 5.2f, y + 1.3f, z); // Offsets pick unrelated parts of the noise,
float qy = perlin.FractalNoise(x + 1.7f, y + 9.2f, z); // so the x and y nudges don't move together.
return perlin.FractalNoise(x + strength * qx, y + strength * qy, z);
}
}
// Explanation:
// - Each helper takes the -1..1 heights from FractalNoise() and returns heights in about the
// same range, so the color thresholds from the height map step still work on the result.
// - They chain: NoiseShapes.Terrace(NoiseShapes.IslandMask(value, nx, ny)) gives a terraced island.
// - WarpedNoise() calls FractalNoise() three times, so it costs three times as much.
// - In Unity you can write UnityEngine.Mathf.Floor/Abs/Sqrt instead; the results are the same.
#include <algorithm>
#include <cmath>
// Step 1: Shape the noise
// -----------------------
// FractalNoise() gives rolling hills everywhere. These four helpers reshape a height
// value (or the coordinates you sample at) so the same noise turns into terraces,
// mountain ridges, an island or twisting coastlines.
// Snap heights to flat steps, like rice terraces or a voxel game's layers.
float terrace(float value, int steps = 6) {
// Round to the nearest step: with 6 steps, heights become ..., -1/6, 0, 1/6, ...
// (std::floor(v + 0.5) rounds the same way as the JavaScript version; std::round wouldn't for negatives.)
return std::floor(value * steps + 0.5f) / steps;
}
// Fold the noise at zero, then flip it, so the old coastline (value 0) becomes a sharp crest.
float ridged(float value) {
return 0.5f - 2 * std::fabs(value); // Crest at 0.5 (snow), valleys fall away on both sides.
}
// Raise the middle of the map and sink the edges, so the land becomes an island.
// nx and ny are the point's position on the map, from 0 to 1.
float islandMask(float value, float nx, float ny, float falloff = 1.1f) {
float dx = nx * 2 - 1; // -1 at the left edge, 0 in the middle, 1 at the right edge.
float dy = ny * 2 - 1;
float d = std::min(1.0f, std::sqrt(dx * dx + dy * dy)); // Distance from the center, capped at 1.
return value + 0.35f - falloff * d * d; // Lift the center a little, push the edges under water.
}
// Domain warping: nudge the sample point by two more noise lookups before sampling.
// The pattern bends into fjords and swirls instead of round blobs.
float warpedNoise(Perlin& perlin, float x, float y, float z, float strength = 1.5f) {
float qx = perlin.FractalNoise(x + 5.2f, y + 1.3f, z); // Offsets pick unrelated parts of the noise,
float qy = perlin.FractalNoise(x + 1.7f, y + 9.2f, z); // so the x and y nudges don't move together.
return perlin.FractalNoise(x + strength * qx, y + strength * qy, z);
}
// Explanation:
// - Each helper takes the -1..1 heights from FractalNoise() and returns heights in about the
// same range, so the color thresholds from the height map step still work on the result.
// - They chain: terrace(islandMask(value, nx, ny)) gives a terraced island.
// - warpedNoise() calls FractalNoise() three times, so it costs three times as much.
// Step 1: Shape the noise
// fractalNoise() gives rolling hills everywhere. These four helpers reshape a height
// value (or the coordinates you sample at) so the same noise turns into terraces,
// mountain ridges, an island or twisting coastlines.
// Snap heights to flat steps, like rice terraces or a voxel game's layers.
FUNCTION terrace(value, steps = 6)
// Round to the nearest step: with 6 steps, heights become ..., -1/6, 0, 1/6, ...
RETURN FLOOR(value * steps + 0.5) / steps
END FUNCTION
// Fold the noise at zero, then flip it, so the old coastline (value 0) becomes a sharp crest.
FUNCTION ridged(value)
RETURN 0.5 - 2 * ABS(value) // Crest at 0.5 (snow), valleys fall away on both sides.
END FUNCTION
// Raise the middle of the map and sink the edges, so the land becomes an island.
// nx and ny are the point's position on the map, from 0 to 1.
FUNCTION islandMask(value, nx, ny, falloff = 1.1)
DECLARE dx = nx * 2 - 1 // -1 at the left edge, 0 in the middle, 1 at the right edge.
DECLARE dy = ny * 2 - 1
DECLARE d = MIN(1, SQRT(dx * dx + dy * dy)) // Distance from the center, capped at 1.
RETURN value + 0.35 - falloff * d * d // Lift the center a little, push the edges under water.
END FUNCTION
// Domain warping: nudge the sample point by two more noise lookups before sampling.
// The pattern bends into fjords and swirls instead of round blobs.
FUNCTION warpedNoise(perlin, x, y, z, strength = 1.5)
// Offsets pick unrelated parts of the noise, so the x and y nudges don't move together.
DECLARE qx = perlin.fractalNoise(x + 5.2, y + 1.3, z)
DECLARE qy = perlin.fractalNoise(x + 1.7, y + 9.2, z)
RETURN perlin.fractalNoise(x + strength * qx, y + strength * qy, z)
END FUNCTION
// Each helper returns heights in about the same -1..1 range, so getColorForHeight() still works.
// They chain: terrace(islandMask(value, nx, ny)) gives a terraced island.
Step 2: Try Them on One Point
Every version prints the same numbers, so you can check your port against ours.
const perlin = new Perlin(777);
const nx = 0.25, ny = 0.6; // A point a quarter of the way across the map, a little below the middle.
const x = nx * 3, y = ny * 3; // The scale generateHeightMap uses by default (xIncrement 0.03 -> 3 cells across).
const height = perlin.fractalNoise(x, y, 0);
console.log("plain: " + height.toFixed(4)); // -0.0243
console.log("terrace: " + terrace(height).toFixed(4)); // 0.0000
console.log("ridged: " + ridged(height).toFixed(4)); // 0.4514
console.log("island: " + islandMask(height, nx, ny).toFixed(4)); // 0.0067
console.log("warped: " + warpedNoise(perlin, x, y, 0).toFixed(4)); // 0.1034
class Program
{
public static void Main(string[] args)
{
Perlin perlin = new Perlin(777);
float nx = 0.25f, ny = 0.6f; // A point a quarter of the way across the map, a little below the middle.
float x = nx * 3, y = ny * 3; // The scale the height map uses by default (xIncrement 0.03 -> 3 cells across).
float height = perlin.FractalNoise(x, y, 0);
Console.WriteLine($"plain: {height:F4}"); // -0.0243
Console.WriteLine($"terrace: {NoiseShapes.Terrace(height):F4}"); // 0.0000
Console.WriteLine($"ridged: {NoiseShapes.Ridged(height):F4}"); // 0.4514
Console.WriteLine($"island: {NoiseShapes.IslandMask(height, nx, ny):F4}"); // 0.0067
Console.WriteLine($"warped: {NoiseShapes.WarpedNoise(perlin, x, y, 0):F4}"); // 0.1034
}
}
#include <iomanip>
#include <iostream>
int main() {
Perlin perlin(777);
float nx = 0.25f, ny = 0.6f; // A point a quarter of the way across the map, a little below the middle.
float x = nx * 3, y = ny * 3; // The scale the height map uses by default (xIncrement 0.03 -> 3 cells across).
float height = perlin.FractalNoise(x, y, 0);
std::cout << std::fixed << std::setprecision(4);
std::cout << "plain: " << height << std::endl; // -0.0243
std::cout << "terrace: " << terrace(height) << std::endl; // 0.0000
std::cout << "ridged: " << ridged(height) << std::endl; // 0.4514
std::cout << "island: " << islandMask(height, nx, ny) << std::endl; // 0.0067
std::cout << "warped: " << warpedNoise(perlin, x, y, 0) << std::endl; // 0.1034
return 0;
}
DECLARE perlin = NEW Perlin(777)
// A point a quarter of the way across the map, a little below the middle.
DECLARE nx = 0.25
DECLARE ny = 0.6
// The scale the height map uses by default (xIncrement 0.03 -> 3 cells across).
DECLARE x = nx * 3
DECLARE y = ny * 3
DECLARE height = perlin.fractalNoise(x, y, 0)
PRINT terrace(height) // 0.0000
PRINT ridged(height) // 0.4514
PRINT islandMask(height, nx, ny) // 0.0067
PRINT warpedNoise(perlin, x, y, 0) // 0.1034
Lab: Shape the Noise
👉 Try this: pick Terraces and tick Island mask for a stepped island; the side view under the map shows each step. Switch to Ridged for a maze of snowy crests, then Warped and drag Strength to 3 to see the coastlines twist. Order matters: the lab applies the island mask before terracing, so the island’s slopes get terraced too.
Domain warping goes much further than this. Our procedural biome generation tutorial warps the warp and builds a whole world on top of it.
Common Pitfalls
- Sampling at whole numbers: Perlin noise is 0 at every integer coordinate. If you pass pixel or tile coordinates straight in (
noise(x, y, 0)with x = 0, 1, 2…), every sample lands on a grid corner and you get a flat zero map. Always scale first:noise(x * 0.05, y * 0.05, 0). - Assuming the wrong range: our
noise()returns roughly −1 to 1, but most values sit well inside that. Across 160,000 samples, our class stayed between −0.81 and 0.76, and fractal noise clusters around 0 even more. Unity’sMathf.PerlinNoisereturns roughly 0 to 1 instead. Check the range before you pick thresholds, and convert with(n + 1) / 2when you need 0 to 1. - The world repeats every 256 units: the
& 255innoise()wraps the grid, sonoise(x + 256, y, z)is exactlynoise(x, y, z). At the height map’s default scale, that’s a repeat about every 85 map widths. For bigger worlds, sample at a lower frequency, or hash coordinates into a larger table. - Float precision far from the origin: in C# and C++ our class uses
float, which keeps about 7 significant digits. At a world coordinate of 100,000, the fractional part that feedsfade()keeps only about 7 bits, and the terrain starts to look stepped. Usedoublefor big worlds, or sample relative to the current chunk. - Grid-aligned features: Perlin noise has a slight bias toward the axes. Look closely at the 2D labs and some ridges and valleys run straight along the grid lines. Rotating the input a little, or switching to Simplex noise, hides it.
Real Games That Use Perlin Noise
- Minecraft (Java Edition): the Minecraft Wiki’s noise generator page lists several Perlin-based generators behind terrain: one acts as the height map, another chooses between two terrain noises, and since version 1.18 the overworld’s multi-noise biome source uses Perlin noise too. Its octave settings run up to 16 layers.
- Factorio: until version 0.13, Factorio’s base terrain noise was “a slightly modified version of Ken Perlin’s Improved Noise.” The developers replaced it because that algorithm was designed for 3D textures rather than huge 2D maps, according to Friday Facts #112 (November 2015). It’s a good reminder that noise is a starting point you tune for your own world.
- Your engine already has it: Unity ships
Mathf.PerlinNoise, and Godot’sFastNoiseLitehas aTYPE_PERLINmode, so the ideas in this tutorial carry straight over. Just check the output range first (see the pitfalls above).
Extensions and Variations
- Biomes and climate: add two more noise layers for temperature and moisture, and pick a biome from the pair. Our procedural biome generation tutorial does exactly that.
- Regions: split the map into territories with Voronoi diagrams, then let noise wobble their borders.
- Caves: use 3D noise as density, solid where it’s above 0, and you get overhangs and tunnels. Our cellular automata tutorial seeds its caves with Perlin noise.
- Animation: sample 1D noise with time as x for wind, flicker and shake. Give each object its own offset so they don’t move in sync.
- Simplex noise: Ken Perlin’s 2001 successor uses triangles instead of squares, which is faster in higher dimensions and has fewer grid artifacts.
What’s the Difference Between Perlin Noise and Simplex Noise?
Perlin noise blends the corners of a square (a cube in 3D, so 8 corners). Simplex noise blends the corners of a triangle (a tetrahedron in 3D, so 4 corners), which makes it cheaper and less grid-aligned. Perlin noise is simpler to understand and still the right choice for most 2D games. Our biome tutorial builds Simplex noise from scratch and races the two head to head.
Final Thoughts
Perlin noise is a small function with a big job. A shuffled table, some dot products and one carefully chosen curve give you a world that’s smooth, random and repeatable all at once. Stack octaves for detail, reshape the heights for character, and you can get a long way before you need anything fancier.
Every lab on this page runs the same code you just read, so if something surprised you, change a number and look again.
Next steps: a height map is the skeleton of a world. The next layer is deciding what goes where. Our Voronoi diagrams tutorial splits the map into organic regions you can turn into biomes, faction territories and dungeon zones. After that, try cellular automata caves, then combining noise and Voronoi into full biome maps.
What would you build with Perlin noise? Tell us in the comments.
Further Learning
- Improving Noise (Ken Perlin, SIGGRAPH 2002): the short paper behind our fade curve and gradients, with his reference implementation
- Implementing Improved Perlin Noise (Ken Perlin, GPU Gems, chapter 5): why the fade curve and gradient set changed
- Making maps with noise functions (Red Blob Games): elevation, moisture, islands and terraces, with interactive demos
- Perlin noise playlist (The Coding Train): a friendly video series that builds it up step by step


This Post Has 0 Comments