mardi 6 août 2019

Java: Randomly generated numbers only appear in small part of given range

I'm working on a game and I want my enemies to spawn with a delay between 1-5 seconds. My code for that part looks like this:

@Override
    public void run() {

    try {
        while (true) {
            Random r = new Random();
            int cooldownTime = r.nextInt((5000 - 1000) + 1) + 1000;
            long lastSpawn = 0;
            long time = System.currentTimeMillis();
            if (time > lastSpawn + cooldownTime) {
                System.out.println(cooldownTime);
                addEnemies();
                lastSpawn = time;
            }

If I understand nextInt correctly this should spawn enemies 1000-5000 ms apart every time, but my results are really weird and I can't quite figure out why. This is an example of what it would look like if I print cooldownTime.

2523

1190

1095

1061

1168

1119

1052

1159

1071

1076

1000

1394

1249

1070

And so on... It seems that the first enemy is truly spawned randomly and the others are always in the low 1000's. This happens every time. Does anyone know why it's like that? I'm quite lost.




Aucun commentaire:

Enregistrer un commentaire