'What is the best way to get random number in JavaScript
I need to get a really random numbers in a game I'm working on. The problem is that the Math.random() gets me exactly same result since it's based on timestamp and I'm using it to position game objects randomly and I need to get random positions instantly. Are there a better way than Math.random()?
https://github.com/suprMax/monkyTime/blob/master/static/monkytime.js#L201
Objects are positioned very close to each other. I tried to make it more random stealing high precision time from request anim frame but no avail.
Solution 1:[1]
The fact that the random generator is seeded from the current time doesn't make it return the same result is subsequent calls. Each time you call it, it will seed itself with the new value, it's only the initial value that is affected by the clock.
Solution 2:[2]
If Math.random() isn't random enough (it's a pseudo-random number generator) then use a true random generator.
It will need to use some remote data for sufficient entropy (such as balls in a blower, white noise, etc). You will probably need to create or use an existing service for this.
Solution 3:[3]
The pseudo random number generator in most browsers should be sufficient for positioning objects in a game. Certainly you should not get the same result over and over again if you have implemented it properly.
If you absolutely need the results to be unpredictable (like for cryptography) you need to look into cryptographically secure PRNGs.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Guffa |
| Solution 2 | alex |
| Solution 3 | Flash |
