Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Move a ball left to right

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading