Java randomization – (minus sign) and (plus sign)
•
Java
Is there any way to add a plus or minus sign randomly? I have a program in which an elf moves on the screen. When you click it, it will reappear in another place I also hope it moves in a random direction At present, I can only set it to move from left to right, or from 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; }
Solution
You can make a variant at any time:
xSpeed = xSpeed * ( random.nextBoolean() ? 1 : -1 ); ySpeed = ySpeed * ( random.nextBoolean() ? 1 : -1 );
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码