如何移动圆圈与for循环?



我想用数组有六个线性移动的点——其中三个是水平移动的,其他是垂直移动的。

下面是我的代码:

let c;
let cspeed = 4 
function setup() {
createCanvas(800, 800);
c=0
}
function draw() {
background(220);

ellipse(c, height / 4, 50, 50);
ellipse(c, height / 2, 50, 50);
ellipse(c, height / 9, 50, 50);
ellipse(height / 4, c, 50, 50);
ellipse(height / 2, c, 50, 50);
ellipse(height / 9, c, 50, 50);
c+=cspeed;
if (c > width || c < 0) {
cspeed *= -1;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

这是另一个包含数组的代码版本。

let height = 400;
let width = 500;
let s = 4;
let d = 50;
function setup() {
createCanvas(width, height);
}
let dots = [{
y: height / 4,
x: 0,
s: s,
d: d,
direction: 'h'
},
{
y: height / 2,
x: 0,
s: s,
d: d,
direction: 'h'
},
{
y: height / 9,
x: 0,
s: s,
d: d,
direction: 'h'
},
{
x: width / 4,
y: 0,
s: s,
d: d,
direction: 'v'
},
{
x: width / 2,
y: 0,
s: s,
d: d,
direction: 'v'
},
{
x: width / 9,
y: 0,
s: s,
d: d,
direction: 'v'
},
]
function draw() {
background(220);
dots.forEach((dot) => {
ellipse(dot.x, dot.y, dot.d, dot.d);
if (dot.direction === 'h') {
dot.x += dot.s
if (dot.x > width || dot.x < 0) {
dot.s *= -1;
}
} else if (dot.direction === 'v') {
dot.y += dot.s
if (dot.y > height || dot.y < 0) {
dot.s *= -1;
}
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

最新更新