-2

so I have a 700x700 screen and I want to create an object (an asteroid) to travel from the left side of the screen to the right side. As soon as it gets out of screen, I want it to spawn back at a random Y ana do the same thing. So far, I have created the object to spawn at a random Y and travel to the right, however, between 0:100 pixels and 600:700 pixels, I have objects and I do not want my object to spawn and travel through those objects. I want the random Y to be between let's say 101 and 599.

if (centerX > width + 200) {
                isTravelling = false;
                centerX = -200;
                centerY = (int)(Math.random());
            }
MrSilent
  • 564
  • 10
  • 25
  • 1
    `Math.random()` returns a positive `double` in the range `[0.0, 1.0)`. May wanna double-check your math. See http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html. – Bucket Nov 22 '13 at 21:18

4 Answers4

5

try

import java.util.Random;

public class YourClass {
    Random rnd = new Random();
    // insert variable declarations here...

    public void yourMethod() {
        if (centerX > width + 200) {
            isTravelling = false;
            centerX = -200;
            centerY = rnd.nextInt(499) + 101;
        }
    }
}
ljgw
  • 2,741
  • 1
  • 19
  • 39
1

Math.floor(Math.random() * 499 + 101) is what you're looking for

Andrei Nicusan
  • 4,486
  • 1
  • 21
  • 36
  • This is inadvisable, as it does not correctly generate a uniformly random value from min to max. – dimo414 Nov 22 '13 at 21:21
1

You could do the following:

min + ((int) (Math.random() * (max - min + 1))

Math.random() generates a double value in the range [0,1) (i.e. including 0 and excluding 1).

Chthonic Project
  • 7,976
  • 1
  • 41
  • 90
  • 1
    This is inadvisable, as it does not correctly generate a uniformly random value from min to max. – dimo414 Nov 22 '13 at 21:21
  • I just found [this explanation](http://stackoverflow.com/questions/738629/math-random-versus-random-nextintint). I didn't know the difference. Thanks for sharing the knowledge :-) – Chthonic Project Nov 22 '13 at 21:26
1

Math.random() returns a double in the range [0-1), which is not what you want.

You can create a new Random() object and call its nextInt(max) method in order to get a uniformly random number between 0 and max (not including max).

private final int MAX = 600;
private final int MIN = 101;
private Random rnd = new Random();

public void doStuff() {
  // before
  if (centerX > width + 200) {
    isTravelling = false;
    centerX = -200;
    centerY = rnd.nextInt(MAX-MIN+1)+MIN;
  }
  // after
}
dimo414
  • 44,897
  • 17
  • 143
  • 228