Letting a loop run forth and back

Do you want to create an animation or a pattern?

A pattern is drawn all the same in every frame. For this, you can use the for loops as you have shown above. I will start with defining every for loop, the ones that draw the rectangle in the downward direction and the for loop to draw the rectangles in the upward direction. Then you can see if there is a pattern to simply the code. My recommendation is: keep it simple at first and keep your code readable.

If you want to do an animation, then I will object you would not need the for loops. Instead, I would use the draw() function, a variable keeping track of the step and a second variable keeping track of position. When you reach a limit (boundary), you reverse the sign of the step:
step = step * (-1); As you can see, step does not have to be 1 but any non-zero value. This is illustrated in the bounce example.

One more thing: I suggest you do this for(int a=....){ ...} Keep your counter definition within the scope of your loops as this is a better practice and it will avoid weird bugs in your code in the future.

Kf

1 Like