BiscuitCookie
BiscuitCookie

Reputation: 709

Java Randomize - (minus) and + (plus)

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

Answers (7)

Wilken
Wilken

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

Kevin K
Kevin K

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

talex
talex

Reputation: 20543

replace xSpeed = random.nextInt(10) with xSpeed = random.nextInt(19)-9

Upvotes: 1

Krycke
Krycke

Reputation: 3186

You can always do a variant of:

xSpeed = xSpeed * ( random.nextBoolean() ? 1 : -1 );
ySpeed = ySpeed * ( random.nextBoolean() ? 1 : -1 );

Upvotes: 7

Dici
Dici

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

Nicholas Betsworth
Nicholas Betsworth

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

KyleK
KyleK

Reputation: 5131

a - b is also a + b * (-1), so you can randomize -1 or 1 and multiply it by xSpeed / ySpeed.

Upvotes: 1

Related Questions