javascript - 如何在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 语句可以处理这个问题,但我必须遗漏一些东西。我遇到了大约一个小时的麻烦,现在我想我会问。谢谢!
解决方案
为对象添加移动方向。当物体出界时改变方向:
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>
推荐阅读
- react-native - 如何使 react-native-raw-bottom-sheet 成为可重用的组件?
- sql - SQL 数据库不保存
- java - 通过 documentID 获取多个特定的 FireStore 文档
- python - 溢出错误:int 太大而无法转换为浮点数
- python - 时间戳与 Firestore 和 Postman 不同
- c++ - 将 boost/文件系统转换为字符串
- python - 将数据框分组并将多列中的数据聚合到新列中
- reactjs - 如何为 Flatlist 的第一个数组赋予不同的样式
- javascript - three.js uv 贴图与 fabric.js
- java - Kotlin + Spring 数据异常(违反约束)