p5.j​​s-random(),高度和宽度未定义? [英] p5.js - random(), height, and width not defined?

查看:74
本文介绍了p5.j​​s-random(),高度和宽度未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用p5.js在画布上反弹球,但似乎未定义widthheightrandom(). 这是我所有的代码:

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

如果我使用JavaScript的Math.random,它可以正常工作.此外,如果我手动将宽度和高度输入为数字(640和480),则效果很好. p5.j​​s是否不应该自动分配heightwidthrandom等? 发生了什么事?

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?

推荐答案

直到之后,您才能使用P5.js函数或变量(包括widthheightrandom()). strong> setup()被调用.这是因为尚未加载P5.js,因此尚未定义它们.您必须确保在setup()被调用之后对P5.js函数或变量的所有调用.

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.

在您的情况下,您直接在顶级上定义dot,这是在调用setup()之前的最开始发生的.您可以通过在dot定义旁边和setup()函数内部放置console.println()调用来进行测试.

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.

基本上,要解决此问题,只需将dot的初始化移到setup()函数中:

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

您可以在 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆