Reputation: 709
is there a way to randomise a plus or Minus character? I have a program where a sprite moves across the screen and when you click it, it reappears in a different place. I also want the direction it moves to be randomized as well. At the moment I can only set it to moving left to right +, or Right to left -.
private int x = random.nextInt(150);
private int y = random.nextInt(500);
private int xSpeed = random.nextInt(10);//Horizontal increment of position (speed)
private int ySpeed = random.nextInt(10);// Vertical increment of position (speed)
public void update() {
x = x +- xSpeed;
y = y +- ySpeed;
}
Upvotes: 3
Views: 6067
Reputation: 207
random.nextInt(1)*2-1
random.nextInt(1) will give you either 0 or 1. Times 2 gives you either 0 or 2. Minus one gives you either -1 or 1
Upvotes: 1
Reputation: 9584
Many have suggested multiplying the speed by 1 or -1, but there is a simpler way that avoids the multiplication, which may be slightly more efficient. Probably not enough to make a noticeable difference on performance, but thought I'd throw it out there anyways.
public void update() {
x = x + (random.nextBoolean() ? xSpeed : -xSpeed);
y = y + (random.nextBoolean() ? ySpeed : -ySpeed);
}
Upvotes: 1
Reputation: 20543
replace xSpeed = random.nextInt(10)
with xSpeed = random.nextInt(19)-9
Upvotes: 1
Reputation: 3186
You can always do a variant of:
xSpeed = xSpeed * ( random.nextBoolean() ? 1 : -1 );
ySpeed = ySpeed * ( random.nextBoolean() ? 1 : -1 );
Upvotes: 7
Reputation: 25980
In the other answers, you have valid solutions for choosing randomly between two values. What I propose you is a way to choose between any number of values :
private static Random rd = new Random();
public static <T> T randomItem(List<T> elts) {
return elts.get(rd.nextInt(elts.size());
}
Upvotes: -1
Reputation: 1803
Consider that there are two possibilities: plus, or minus. So simply generate a random number with 2 possible outcomes, and use this to determine the sign (plus or minus):
public int getRandomSign() {
Random rand = new Random();
if(rand.nextBoolean())
return -1;
else
return 1;
}
public void update() {
x = x + xSpeed * getRandomSign();
y = y + ySpeed * getRandomSign();
}
Upvotes: 1
Reputation: 5131
a - b
is also a + b * (-1)
, so you can randomize -1 or 1 and multiply it by xSpeed / ySpeed.
Upvotes: 1