Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a simple javascript game and I'm initializing their positions on the y axis using random numbers. How can I ensure that they are reasonably spaced apart? My simple algorithm is:

 y = (Math.random()*1000%600);

However I frequently get enemies almost directly on top of each other. This is a huge problem for the game, since it's a word game and the enemies have text on their center, that if overlapped makes them impossible to kill since you can't see the words. Any advice would be appreciated! I'm pretty new to making games in general so this has all been a learning experience for me!

share|improve this question
Hate to say it but random numbers are(n't) random. Also, in my experience compilers usually evaluate % before multiplication. so you may want to add some parentheses in there. – UnderscoreZero Nov 8 '13 at 21:18
A simple solution is to divide the spawn area into a grid (for so say your screen has 5 rows and 10 columns), then pick a random grid space for each enemy (make sure no more than one enemy per space), then just get two random variance values (how far they away they are from the center of the grid space). – Benjamin Danger Johnson Nov 8 '13 at 21:19
up vote 1 down vote accepted

Just add a small constant amount to your random value to ensure separation.

y = ((Math.random()*1000)%600) + 10;

All in all, this is going to be a play testing issue to find out what a good distance is. You can also experiment with other random distribution methods. For example, you can have each enemy placed 100 units apart, and that position is randomized by +- 40 units.

With basic questions like this is good to just experiment and find something that works for you. Ideally starting with something static and then making it random.

share|improve this answer
The grid method from Benjamin Danger Johnson in combination with your method worked perfectly! Thanks so much! I don't think I would have thought of that on my own. – Samuraisoulification Nov 9 '13 at 2:28
you can also use a less uniform variant : choose randomly the distance, with a min and max distance : y = prevY + min + Math.random()*(max-min). – GameAlchemist Nov 9 '13 at 15:56

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.