〰️ Randomness & Noise
Randomness is used extensively in game development and computer graphics. It is for instance used to generate procedural content, such as terrain or weather, or to create animations and effects.
Math.random will give you a random float between 0 and 1. If you want to specify lower and upper bounds more conveniently than doing math over
Math.random, or using integers instead of floats, you can use Lodash's
random (opens in a new tab), or random (opens in a new tab).
Math.random will often get the job done, but you will sometimes need more control over the randomness.
If you want the randomness to be deterministic, you can use a seedable pseudo-random number generator (PRNG). A seed is a value that is used to initialize the generator. If you use the same seed, you will get the same sequence of numbers, which will let you generate the same content every time. Here are some PRNG libraries:
- Prando12012k/w2y years
- alea9044k/w2y years
- seedrandom.js2k2M/w4y years
- random-js6004y years
- Number Generator10600/w1y year
- random-seed90100k/w8y years
- seed-random401M/w10y years
Random numbers distributed on 1, 2, 3, or more dimensions are called noise. Using
Math.random for this will give you white noise. White noise has its use cases, but it is not very useful for things like generating terrain.
If you want to generate random terrain or clouds for instance, you need gradient noise with peaks and valleys. You can use a Perlin noise (see this article (opens in a new tab) for more details). Perlin noise was created by Ken Perlin in 1983. He later on released Simplex noise in 2001, which has some improvements (opens in a new tab) over Perlin noise, but was patented until January 8th 2022. OpenSimplex noise (opens in a new tab) was developed to overcome the patent issue of Simplex noise.
- tumult40150/w4y years
- open-simplex-noise130200/w2y years
In the case of terrain, 2D noise can be used to generate the heightmap of a 3D map but you won't get any cave or any part of the ground with void under it. To get that, you can either use 3D noise, combine multiple noises, use a Marching Cube algorithm (opens in a new tab), or generate an initial terrain and fine-tune it manually. For texturing, you might want to look into texture splatting (opens in a new tab) (Three.js forum thread (opens in a new tab), three-landscape (opens in a new tab), THREE.Terrain (opens in a new tab)).
This SimonDev video (opens in a new tab) illustrates various usages of randomness and noise in computer graphics.