I need a quick explanation how this works cause i don't get it

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.

1 Like

s means speed here

It gets added to the position x, y throughout

when you change s the direction changes

1 Like

Yes, exactly.

  • s1 controls the motion in the x direction
  • s2 controls the motion in the y direction
  • a -1 value decreases the affected positional coordinate
  • a 0 value keeps the affected positional coordinate constant
  • a +1 value increases the affected positional coordinate
  • the conditional blocks change the values of s1 and s2 when a boundary is reached
1 Like