Make the rectangle move to the opposite corner

hello! I need your help, please.
I have to make the rectangle move to the opposite corner and after disappearing in the lower corner, it should appear again in the upper opposite corner. The condition is to use the modulo-operator.
I don’t know what I did wrong, but only the red rectangle returns, the others do not reappear.

float x = 0;
float y = 0;
float a = 0;
float z= 380;
float speed = 1;
void setup() {

void draw() {
  x = (x + speed)% width;
  z= (z-speed)% width;
  y= (y+speed)%height;
  fill (155);
  rect(z,z, 100,100);
  rect (x,z,100,100);


Interesting question! :slightly_smiling_face:

I did a quick google search. And found this on stackoverflow:

I played with the numbers a bit. As far as I can tell the problem is here:

One of the proposed solutions is the following expression (see stackoverflow post for author attribution):
“Your expression should be ((x-1) + k) % k . This will properly wrap x=0 around to 11. In general, if you want to step back more than 1, you need to make sure that you add enough so that the first operand of the modulo operation is >= 0.”

I tried doing this:

z = ((z - speed)+z) % 380;

And no, it is not the solution.
HOWEVER, it does bring the green square back to the top right. But it now bounces left to right as it moves down the canvas. So further experimentation may be worth investigating.

Also, a word of advice. To eliminate distraction, comment out the bottom 2 rectangles.
Once you solve the movement of the green rectangle, then test with the rest of the rectangles.
Good luck!


Hello @add,

A hint:

float x = 0;
void setup() 
  size(300, 100);

void draw() 
  x = (x+1)%width;
  println(x, 300-x); // Useful!
  circle(x, 50, 10);
  circle(300-x, 50, 10); // Interesting! It is going the other direction...


1 Like

thank you very much @debxyz and @glv . I did it, using instead of z 380-x.