Search code examples
javaprocessing

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.

color blau      = #2E3BFF; //Color blau
color vermell     = #FF2E2E; //Color vermell
float position_X;   //Variable per la posició X

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 
    }