I wanna have six linearly moving dots -- three of them horizontally, others vertically using an array.
here is my code:
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>
CodePudding user response:
This is another version of your code that incorporates an array.
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>