let x
let y
let s1
let s2
function setup() {
createCanvas(400, 400);
frameRate(60)
x = 50
y = 50
s1 = 1
s2 = 1
}
function draw() {
background('black');
ellipse(x,y,100)
x += s1
y += s2
if (y > 350 && x > 350){
s2 *= -1
s1 *= 0}
if (x > 350 && y < 50){
s1 = -1
s2 = 1
}
if (x < 50 && y > 350){
s1 = 0
s2 = -1
}
if (x < 50 && y < 50){
s1 = 1
s2 = 1
}
}
I don’t really get how this code works. I got it from a friend without any explanation. Can someone please write e explanation on the basic stuff and what does what so I can make the sam but on my own.
It would be best to add semicolons at the ends of statements, and to format the code according to its block structure. That would make it easier to view that structure, and thereby to understand the logic of the code.
Here is the code, reformatted:
let x;
let y;
let s1;
let s2;
function setup() {
createCanvas(400, 400);
frameRate(60);
x = 50;
y = 50;
s1 = 1;
s2 = 1;
}
function draw() {
background('black');
ellipse(x, y, 100);
x += s1;
y += s2;
if (y > 350 && x > 350) {
s2 *= -1;
s1 *= 0;
}
if (x > 350 && y < 50) {
s1 = -1;
s2 = 1;
}
if (x < 50 && y > 350) {
s1 = 0;
s2 = -1;
}
if (x < 50 && y < 50) {
s1 = 1;
s2 = 1;
}
}
Notice the headers of the conditional blocks, such as this one:
if (y > 350 && x > 350) {
The block changes the direction of motion of the ellipse when it hits the lower right corner of the canvas. The other blocks also change the direction of motion of the ellipse when it reaches boundaries, which keeps the ellipse within the canvas.