如何使变量随机等于2个数字中的1个? (处理中)

时间:2019-02-12 01:43:32

标签: processing

我是第一次尝试做Pong。我并不总是希望球每次都加3到右下角。我将如何做到这一点,使其可以执行3或-3,但两者之间没有数字?我知道“ ||”不适用于整数,并且“ random(-3,3)有机会给我像” 0.1“这样的数字,但在这里实际上并不起作用。 代码:

float circleX = 640/2;
float circleY = 360/2;
float xSpeed = 3;
float ySpeed = 3;
float Color = (255);
float circleHeight = 32;
float circleWidth = 32;
float xAcceleration = -1.0;
float yAcceleration = -1.0;
float paddleColor = 255;
float MyPaddleX = 630;
float OpPaddleX = 10;
float MyPaddleWidth = 10;
float OpPaddleWidth = -10;


void setup() {
  size(640, 360);
  frameRate(60);
}

void draw() {
  background(0);

  //Ball
  fill(Color);
  ellipse(circleX, circleY, circleWidth, circleHeight);
  xSpeed = //(WHAT TO PUT HERE?)
  circleX = circleX + xSpeed;
  circleY = circleY + ySpeed;

 //My Paddle
 fill(paddleColor);
 rect(MyPaddleX,mouseY,MyPaddleWidth,100);

  //Bouncing
  if (circleX >= OpPaddleX && OpPaddleX + OpPaddleWidth >= circleX) {
    xSpeed = xSpeed * xAcceleration;
  }
  // Top/Bottom Bouncing
  if (circleY > height || circleY < 0) {
    ySpeed = ySpeed * yAcceleration;
  }
  //My Paddle Bounceback
  if (circleY >= mouseY && circleY <= mouseY + 100) {
    if (circleX >= MyPaddleX && circleX <= MyPaddleX + 3)
    xSpeed = xSpeed * xAcceleration;

  }
  //Opponent Paddle
  fill(paddleColor);
  rect(OpPaddleX,circleY - 50,OpPaddleWidth,100);

  //if (circleX < OpPaddleX || circleX > MyPaddleX) {
  //  circleX = width/2;
  //  circleY = height/2;
  //  xSpeed = 0;
  //  ySpeed = 0;
  //}

}

1 个答案:

答案 0 :(得分:0)

您可以在01之间生成一个数字,然后将该生成的数字与0.5进行比较以在代码中“翻转硬币”。

以这种方式思考:调用random(1)时,您将获得01之间的值。这些值的一半将小于0.5,另一半将大于(或等于)0.5

因此您可以执行以下操作:

float x;

if(random(1) < .5){
  x = -3;
}
else{
  x = 3;
}

您可以使用else if语句将其扩展为从更多数字中选择,或者使用三元运算符将其缩短为一行代码:

float x = random(1) < .5 ? 3 : -3;