如何在 p5js 中来回移动对象 javascript

How to move an object back and forth in p5js javascript

经过几个小时的工作和研究(我刚开始学习 p5js 和 javascript)我有大约 50 行代码创建了一个圆网格并开始将它们移动到 canvas.在进入我的问题之前,我将分享代码。

var circles = [];

function setup() {
  createCanvas(500, 500);
  for (var a = 50; a < width - 300; a += 20) {
    for (var b = 50; b < height - 300; b += 20) {
      circles.push(new Circle(a, b));
    }
  }
}

function draw() {
  background(50);
  for (var b = 0; b < circles.length; b++) {
    circles[b].show();
  }
}

function Circle(x, y) {
  this.x = x;
  this.y = y;

  this.show = function() {
    fill(255);
    noStroke();
    ellipse(this.x, this.y, 10, 10);
    if (this.x < 51) {
      this.x += 1
      this.y += 1
    } 
    if (this.x < 430) {
      this.x += 1
      this.y += 1
    }
    if (this.x > 430) {
      this.x -= 1
      this.y -= 1
    }
    if (this.x < 51) {
      this.x += 1
      this.y += 1
    } 
  }
}

我想做的是将这个从 (50,50) 开始的圆圈网格移动到右下角。一旦它达到 (width-50,height-50),我希望运动倒转回到起点,然后以另一种方式返回。这段代码成功地将圆圈移到了右下角,但出了点问题。圆圈不会反转它们的运动,相反,它们会变得混乱。我认为 if 语句可以处理这个问题,但我一定遗漏了一些东西。我麻烦了大约一个小时,现在我想我会问。谢谢!

为对象添加移动方向。物体出界时改变方向:

var circles = [];

function setup() {
    createCanvas(500, 500);
    for (var a = 50; a < width - 300; a += 20) {
        for (var b = 50; b < height - 300; b += 20) {
            circles.push(new Circle(a, b));
        }
    }
}

function draw() {
    background(50);
    for (var b = 0; b < circles.length; b++) {
        circles[b].show();
    }
}
    
function Circle(x, y) {
    this.x = x;
    this.y = y;
    this.dx = 1;
    this.dy = 1

    this.show = function() {
        fill(255);
        noStroke();
        ellipse(this.x, this.y, 10, 10);

        this.x += this.dx
        this.y += this.dy

        if (this.x < 51 || this.y < 51) {
            this.dx = 1
            this.dy = 1
        } 
        if (this.x > 430 || this.y > 430) {
            this.dx = -1
            this.dy = -1
        }
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>

如果不想单独移动对象,则必须对所有对象使用 1 个移动方向:

var circles = [];

function setup() {
    createCanvas(500, 500);
    for (var a = 50; a < width - 300; a += 20) {
        for (var b = 50; b < height - 300; b += 20) {
            circles.push(new Circle(a, b));
        }
    }
}

var dx = 1
var dy = 1
function draw() {
    background(50);
    mx = dx
    my = dy
    for (var b = 0; b < circles.length; b++) {
        circles[b].show(mx, my);
    }
}
    
function Circle(x, y) {
    this.x = x;
    this.y = y;

    this.show = function(mx, my) {
        fill(255);
        noStroke();
        ellipse(this.x, this.y, 10, 10);

        this.x += mx
        this.y += my

        if (this.x < 51) {
            dx = 1
            dy = 1
        } 
        if (this.x > 430) {
            dx = -1
            dy = -1
        }
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>