首页 > 解决方案 > p5js 在主范围内使用循环函数

问题描述

所以我在 p5js 中有这个非常基本的例子:

var e = 1;

function setup() {
    window.canvas = createCanvas(200, 200);
}

function draw() {
    fill(255, 255, 0);
    ellipse(50 + e, 50, 30);
    e++;

    noLoop();
}

如果我们暂时忽略noLoop(),这段代码只是复制一个圆圈并将其向右移动。

现在,我试图通过添加以下内容来控制正在播放的帧数:

function makeOneMove() {
    loop();
}

因此,每当我makeOneMove()像在脚本中那样调用时,我都希望它播放一帧。

但是,遗憾的是我收到了这个错误:

未捕获的 ReferenceError:未定义循环

所以我的问题是,我怎样才能使用它loop()noLoop()只在 p5 的函数(如 setup 或 draw)中工作的函数。

标签: javascriptp5.js

解决方案


要逐帧执行此操作,您需要确保loop()在您的setup()方法中使用它,如下所示:

var e = 1;

function setup() {
  createCanvas(200, 200);
  makeOneMove(); // call makeOneMove in `setup`
}

function makeOneMove() {
  loop();
}

function draw() {
  background(255); // used to remove the "trail" of circles (remove if trail is wanted)
  fill(255, 255, 0);
  ellipse(50 + e, 50, 30);
  e++;
  noLoop();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

您可以控制outside of和 inside of的值,而不是控制何时draw()被调用。这样,就像被一遍又一遍地重复调用一样,它将采用 的新值并在该新偏移位置绘制圆。出于演示目的,我添加了一个在您单击时将调用的方法:edraw()makeOneMove()draw()emouseClicked()makeOneMove()

var e = 1;

function setup() {
  createCanvas(200, 200);
}

function makeOneMove() {
  e++;
}

function draw() {
  background(255); // used to remove the "trail" of circles (remove if trail is wanted)
  fill(255, 255, 0);
  ellipse(50 + e, 50, 30);
}

function mouseClicked() {
  makeOneMove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>

对于多个圆圈/对象,这取决于您如何表示数据/对象。最好的方法是使用对象(例如通过创建一个Class),并更改每个对象的偏移量(即:e值):

class Circle {
  constructor(x, y, r, color) {
    this.x = x;
    this.y = y;
    this.r = r;
    this.color = color;
    this.offset = 1; // (circles own `e` value)
  }
}

var objects;

function setup() {
  createCanvas(200, 200);
  objects = [ // store all your onscreen objects in an array
    new Circle(50, 50, 30, color(255, 255, 0)), // original object you had
    new Circle(50, 100, 50, color(0, 255, 0))
  ]; 
}

function makeOneMove(objectIndex) {
  objects[objectIndex].offset++;
}

function draw() {
  background(255); // used to remove the "trail" of circles (remove if trail is wanted)
  for(const circle of objects) {// loop through all objects in your `objects` array
    // Draw the given object/circle
    fill(circle.color);
    ellipse(circle.x + circle.offset, circle.y, circle.r);
  }
}

function mouseClicked() {
  makeOneMove(0); // make object 0 in array move (for demo)
}

function keyPressed() {
  makeOneMove(1); // make object 1 in array move (for demo)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>


推荐阅读