首页 > 解决方案 > 如何在p5js javascript中来回移动对象

问题描述

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

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 语句可以处理这个问题,但我必须遗漏一些东西。我遇到了大约一个小时的麻烦,现在我想我会问。谢谢!

标签: javascriptp5.js

解决方案


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

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>


推荐阅读