Java Randomize - (minus) and + (plus)
Is there a way to randomize the plus or minus symbol? I have a program where a sprite moves across the screen and when you click it, it appears again in a different location. I also want the direction it was moving in to be randomized as well. At the moment I can only set it to left or 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;
}
+3
source to share
6 answers
Please note that there are two possibilities: plus or minus. So just create a random number with two possible results and use that 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();
}
+1
source to share
Many have suggested multiplying the speed by 1 or -1, but there is an easier way to avoid the multiplication, which may be slightly more efficient. Probably not enough to make a noticeable difference in performance, but I thought I'd throw it away anyway.
public void update() {
x = x + (random.nextBoolean() ? xSpeed : -xSpeed);
y = y + (random.nextBoolean() ? ySpeed : -ySpeed);
}
+1
source to share