Random function help please.

Soldato
Joined
18 Jun 2010
Posts
6,641
Location
Essex
I'm making an asteroid belt for my project it consists of a lot of objects that are random put 300 pixels from the sun then add Math.random() * 300 so that it will randomly be between 300-600 distance away from the sun. However I wanted it to be less far away and more nearer to the sun, so I did the following:

300 + Math.random()*300*Math.random()

Therefore it is less likely to be nearer to 600 and more likely to be nearer to 300.

What I want now is for there to be lots in the middle of the range 300-600 and less near the sun and less far away but I can't get my head around how to do it.

Any help would be appreciated, cheers.

EDIT:

Wow, the second I stopped writing I figured it out.

if (Math.random() < 0.5)
{
450 + Math.random() * 150 * Math.random()
}
else
{
450 - Math.random() * 150 * Math.random()
}
 
Last edited:
Soldato
OP
Joined
18 Jun 2010
Posts
6,641
Location
Essex
Just use a normal distribution.

See my edit, it's fine now.

Looks like this now ^^

orrery.png
 
Last edited:
Soldato
OP
Joined
18 Jun 2010
Posts
6,641
Location
Essex
Thanks man! There's way more to it, (it's animated) and loads of different modes.

Obviously the art side of it is terrabad but it's a computer science degree not an art degree ^^ :).
 
Soldato
OP
Joined
18 Jun 2010
Posts
6,641
Location
Essex
I had a rethink of this the other day, pointless bump but in case anyone was wondering.

You could do something along the lines of
//would return a number between 1 and -1 multiplied by the range
// e.g. range = 3. between 3 and -3.
Math.sin(Math.random() * 2 * Math.pi) * range

It's one line rather than a conditional. Then you could also times it all by Math.random() again if you wished to make things more likely to be closer to the middle ^^
 
Back
Top Bottom