如何在没有页面刷新/ mouseClicked的情况下生成随机数

时间:2016-11-13 06:15:47

标签: javascript random

所以我知道因为随机数是在设置中生成的我只得到一个值但是当我在绘图中调用随机数时我得到的数字太多了。我需要的是当音调离开屏幕时,产生一个新数字并根据该数字抛出新音高。

var pitch; 
var speed;
var xMovement; 
var x = 300;
var y = 200; 
var a = 400;
var b = 200; 
var num;

function preload() {
 data = loadJSON('pitcherData.json');  
}

  function setup() { 
  createCanvas(600, 600);
  num = random(0,100);
} 

function draw() { 
  background(220);
  randomPitch(); 



}

function fastball(){
  var FAMax = data.pitchers[0].pitches[0].MaxVelo;
  var FAMin = data.pitchers[0].pitches[0].MinVelo;
  var FAxMov = data.pitchers[0].pitches[0].xMov;
  //mapping of maximum velocity 
  var FAMapMax = map(FAMax, 50, 101.3, 0, 8);
  //mapping of minimum velocity
  var FAMapMin = map(FAMin, 50, 101.3, 0, 8); 
    // mapped xMov of fastball
  var FAMapMov = map(FAxMov, -9.0, 5.0, -7, 7); 


  // pitch velo will randomly vary between max and min
  var FArandomSpeed = random(FAMapMax, FAMapMin); 

  fill(0,200,100);
  ellipse(x, y, 30, 30);  
  y = y + FArandomSpeed; 
  if(y>400) {
  x = x + FAMapMov;
  } 
  if (y > height*2) {
  x = 300; 
  y = 200; 
  }
}

function slider(){
  var SIMax = data.pitchers[0].pitches[2].MaxVelo;
  var SIMin = data.pitchers[0].pitches[2].MinVelo;
  var SIxMov = data.pitchers[0].pitches[2].xMov;
  console.log("Mov: " + SIxMov);
  var SIMapMax = map(SIMax, 50, 101.3, 0, 8);
  var SIMapMin = map(SIMin, 50, 101.3, 0, 8);
  var SIMapMov = map(SIxMov, -9.0, 5.0, -7, 7);
  console.log(SIMapMov);
  var SIrandomSpeed = random(SIMapMax, SIMapMin);

  fill(200,175,50);
  ellipse(a, b, 30, 30);
  b = b + SIrandomSpeed;
  if (b > 500) {
    a = a + SIMapMov;
  }

  if(b > height*2) {
    a = 400; 
    b = 200;

  }
}

function randomPitch(){
  if (num >= 30) {
    fastball();
  } else {
    slider();
  }
  if (y > height || b > height){
  num;
}
text(num, 200, 200)
}

1 个答案:

答案 0 :(得分:0)

num = random(0, 100)放入randomPitch函数中,以便每次需要随机音高时都会创建新值num

function randomPitch(){
  num = random(0, 100)
  if (num >= 30) {
    fastball();
  } else {
    slider();
  }
  /* etc */
}