1

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.

Max
  • 1,149
  • 3
  • 10
  • 20
  • Here are answers of your question: http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript – Riz May 29 '12 at 13:45
  • @dev: ...and they all use `Math.random()`, except the ones that suggests to use AJAX to call a server... – Guffa May 29 '12 at 13:52
  • "Math.random() gets me exactly same result" - show us your code and we can tell you where the bug is. – AakashM May 29 '12 at 13:54
  • https://github.com/suprMax/monkyTime/blob/master/static/monkytime.js#L201 – Max May 29 '12 at 14:04

3 Answers3

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.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • I agree and it looks rather random here http://jsfiddle.net/w7uYL/ . Its weird that I'm getting objects positioned really close to each other – Max May 29 '12 at 14:26
0

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.

alex
  • 479,566
  • 201
  • 878
  • 984
0

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.

Flash
  • 15,945
  • 13
  • 70
  • 98