-3

I want to make the speed on vector x random with min -5 and max 5. Everytime I run the game it is crashing. the problem in random because when i set velX = 2 or 3 it works perfectly, help me please. (Sorry for my english, i hope you understand me)

velX = random.nextInt(5 - -5) + -5;
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588

1 Answers1

0

You probably want this:

velX = random.nextInt(10) - 5;

(Generate a random int btw 0 and 10, then subtract 5, giving you a range btw -5 (inclusive) and 5 (exclusive). If you want 5 to be inclusive as well, change the nextInt() parameter to 11.


OTOH you probably shouldn't use a real random, but rather a bell curve (values in the middle appearing more often than outliers). One easy way to achieve that is to have a List with all the values (once for outliers and more often for middle values) and pick randomly among them. You might want to play around with the values to see what works best for you.

// do this only once, during initialization
List<Integer> values = new ArrayList<>();
values.add(-5);
values.addAll(Collections.nCopies(2, -4));
values.addAll(Collections.nCopies(3, -3));
values.addAll(Collections.nCopies(5, -2));
values.addAll(Collections.nCopies(8, -1));
values.addAll(Collections.nCopies(12, 0));
values.addAll(Collections.nCopies(8, 1));
values.addAll(Collections.nCopies(5, 2));
values.addAll(Collections.nCopies(3, 3));
values.addAll(Collections.nCopies(2, 4));
values.add(5);

// do this every time
velX = values.get(random.nextInt(values.size()));
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588