p5.js - random()、高度和宽度未定义?

p5.js - random(), height, and width not defined?

我正在尝试使用 p5.js 让球在 canvas 周围反弹,但似乎 widthheightrandom()没有定义。 这是我的所有代码:

function setup() {
  createCanvas(640,480);
  background(240);
}

var dot = {
  x: random(width), 
  y: random(height), 
  size: 50,
  r: 255,
  g: 0,
  b: 0,
  speedX: 5,
  speedY: 5
};

function draw() {
  background(240);
  fill(dot.r, dot.g, dot.b);
  ellipse(dot.x, dot.y, dot.size, dot.size);
  if (dot.x >= 615 || dot.x <= 25) { //if the ball is out of screen horizontally
    dot.speedX = dot.speedX * -1;
  } 

  if (dot.y >= 465 || dot.y <= 25) { //if the ball is out of screen vertically
    dot.speedY = dot.speedY * -1;
  }

  dot.x = dot.x + dot.speedX;
  dot.y = dot.y + dot.speedY;
}

如果我使用 JavaScript 的 Math.random,它工作正常。此外,如果我手动输入宽度和高度作为数字(640 和 480),它工作正常。 p5.js 不应该自动分配 heightwidthrandom 等吗? 怎么回事?

您不能使用 P5.js 函数或变量(包括 widthheightrandom()),直到 after setup() 被调用。那是因为 P5.js 还没有加载,所以它们没有被定义。您必须确保对 P5.js 函数或变量的任何调用都在调用 setup() 之后。

在您的情况下,您直接在顶层定义 dot,这发生在最开始,在调用 setup() 之前。您可以通过将 console.println() 调用放在 dot 定义旁边以及 setup() 函数内来测试这一点。

要解决此问题,请将 dot 的初始化移动到 setup() 函数内部:

var dot;

function setup() {
  createCanvas(640,480);
  
  dot = {
      x: random(width), 
      y: random(height), 
      size: 50,
      r: 255,
      g: 0,
      b: 0,
      speedX: 5,
      speedY: 5
  }

  background(240);
}

function draw() {
  ...

您可以在 the P5.js FAQ 中阅读更多相关信息。