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

帅比萌擦擦* 提交于 2019-12-11 06:09:52

问题


I'm trying to make a ball bounce around the canvas using p5.js, but it seems that width, height, and random() aren't defined. Here's all my code:

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;
}

If I use JavaScript's Math.random, it works fine. Furthermore, it works fine if I manually input the width and height as numbers (640 and 480). Shouldn't p5.js automatically assign height, width, random, etc.? What's going on?


回答1:


You can't use P5.js functions or variables (including width, height, and random()) until after setup() is called. That's because P5.js isn't loaded yet, so they aren't defined. You have to make sure any calls to P5.js functions or variables are after setup() is called.

In your case, you're defining dot directly at the top level, which happens at the very beginning, before setup() is called. You can test this out by putting console.println() calls next to your dot definition, and inside the setup() function.

Basically, to fix this, just move the initialization of dot to be inside the setup() function:

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() {
  ...

You can read more about this in the P5.js FAQ.



来源:https://stackoverflow.com/questions/47428208/p5-js-random-height-and-width-not-defined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!