〰️ 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
, or random. Math.random
will often get the job done, but you will sometimes need more control over the randomness.
Seedable Pseudo-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:
- StarsNPMTSMaintained
- 14025k/w
- 12012k/w4 years
- N/A145k/w
- 80020/w
- 9044k/w3 years
- 2k2M/w5 years
- 60060k/w5 years
- 10600/w2 years
- 90100k/w9 years
- 401M/w11 years
Compare on NPMTrends and Star History (requires a GH token)
About these numbers and colors
Some randomness libraries also support fake data generation. For instance, Chance, Faker, or Casual.
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.
Perlin noise and Simplex noise
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 for more details). Perlin noise was created by Ken Perlin in 1983. He later on released Simplex noise in 2001, which has some improvements over Perlin noise, but was patented until January 8th 2022. OpenSimplex noise was developed to overcome the patent issue of Simplex noise.
Compare on NPMTrends and Star History (requires a GH token)
About these numbers and colors
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, or generate an initial terrain and fine-tune it manually. For texturing, you might want to look into texture splatting (Three.js forum thread, three-landscape, THREE.Terrain).
Note that there are other types of noises such as the Worley noise, which can for instance be used for shaders.
This SimonDev video illustrates various usages of randomness and noise in computer graphics.