p5.js入门学习-数组3

76 阅读2分钟

当我们逐渐深入学习,你会发现数组中的元素种类可以是千变万化的,本示例我们来了解一下如何创建对象,将对象作为数组元素,并对每一个对象单独控制其运动方式。

// class 是定义类的关键词,当我们将该类生成为实例的时候,就被称之为对象了。
class Module {
  // 在类中会有一些拥有特殊含义的函数,比如constructor会在生成实例的时候,自动运行。
  constructor(xOff, yOff, x, y, speed, unit) {
    this.xOff = xOff;
    this.yOff = yOff;
    this.x = x;
    this.y = y;
    this.speed = speed;
    this.unit = unit;
    this.xDir = 1;
    this.yDir = 1;
  }
  // 自定义函数 update:用于更新坐标信息
  update() {
    // 新坐标 = 原坐标+速度*方向
    this.x = this.x + this.speed * this.xDir;
    // 每一个对象仅限在自己的单元中移动,当超过界限后,方向取反
    if (this.x >= this.unit || this.x <= 0) {
      this.xDir *= -1;
      this.x = this.x + 1 * this.xDir;
      this.y = this.y + 1 * this.yDir;
    }
  }
  // 自定义函数 draw:用于绘制圆
  draw() {
    fill(255);
    ellipse(this.xOff + this.x, this.yOff + this.y, 6, 6);
  }
}
// 创建全局变量
let unit = 40;
let count;
// 画布中的每一个点都是该数组中的每一个元素(对象)
let mods = [];
function setup() {
  // 画布:720 * 360
  createCanvas(720, 360);
  noStroke();
  // 计算行列分别都有多少个对象需要被创建
  let wideCount = width / unit;
  let highCount = height / unit;
  // 对象总数
  count = wideCount * highCount;
  let index = 0;
  // 凡是类似于平面扫描的,都需要用到嵌套循环
  for (let y = 0; y < highCount; y++) {
    // 遍历第y行对象
    for (let x = 0; x < wideCount; x++) {
      // 创建对象(Module),constructor函数中的变量都会成为该对象的属性
      // 每一个对象都会拥有默认值,比如默认的坐标位置,默认的随机速度
      mods[index++] = new Module(
        x * unit,
        y * unit,
        unit / 2,
        unit / 2,
        random(0.05, 0.8),
        unit
      );
    }
  }
}
function draw() {
  background(0);
  // 进入绘图函数后,遍历每一个对象,并让每一个对象进行坐标更新+形状绘制。
  for (let i = 0; i < count; i++) {
    mods[i].update();
    mods[i].draw();
  }
}
new p5();

p5js 开源社区 - 乐述云享 (aleshu.com)