I am trying to come out with a code that moves a square from left to right at each direction the colour of it has to change.
It must start from the left edge and once it reaches the right edge, then goes back to the right, without changing the Y position.
I did a code, but it doesn’t work.
color blau = #2E3BFF; //Color blau
color vermell = #FF2E2E; //Color vermell
float position_X; //Variable per la posició X
float position_Y; // Variable per la posició Y
float size=50; //Mida del costat del quadrat
boolean move;
void setup () {
// Preparem el llenç. La mida és de 1000 x 500 píxels
size (1000, 500);
frameRate(60); //Velocitat que s'executa el draw()
background(0); //Color fons negre
position_X= 0; //Posició inicial del quadrat al costat esquerre del llenç
position_Y= 200; //Alçada inicial del quadrat en el llenç
move=true;
}
void draw () {
background(0); //color del fons
square (position_X, position_Y, size);
while (move==true){
if (position_X==width){
move=false;}
fill (vermell); //Color del quadrat
position_X=position_X+5; //Es mou de dreta a esquerra
}
while (move==false){
if (position_X==0){
move=true;
}
fill (blau); //Color del quadrat
position_X=position_X-10;} //Es mou de dreta a esquerra
}
>Solution :
The while loops need to be an if. the draw function is the loop. right now you are moving the position_x all the way to the end and back before you reprint the square.
if (move==true){
if (position_X==width){
move=false;}
fill (vermell); //Color del quadrat
position_X=position_X+5; //Es mou de dreta a esquerra
}
if (move==false){
if (position_X==0){
move=true;
}
fill (blau); //Color del quadrat
position_X=position_X-10;} //Es mou de dreta a esquerra
}