I’m having difficulty figuring out how to reverse the direction of an animated loop when it reaches the end of an array. I found an example online that creates two “states” with an additive and subtractive loop within each respective state, but I have not been able to implement it.
Below is a simplified example of what I’m attempting. Would be grateful for someone’s advice on how to reverse the direction of the point when the last value within the array (14) is reached and, then, how to reverse it again when it returns to the array’s first value.
let array1 = [];
let a = 0;
let i = 0;
function setup() {
createCanvas(400, 200);
array1 = [2,4,6,8,10,12,14];
}
function draw() {
background(220);
frameRate(1);
strokeWeight(10);
stroke(255);
point(array1[i]*20,100);
i=i+1;
}
Previous solutions are fine and answer to your question.
To open up to other solutions, i often prefer to use a generator:
function * loopOnArray(someArray){
while (true) {// infinite loop
for (let aPoint of someArray){
yield aPoint
}
// once done reverse the array
someArray= someArray.reverse();
} // and loop again (while true)
}
Within an infinite loop (while true) this generator distributes points one per one (each yield) from the array and, once done, reverse this array and leaves for a new round.
To use it :
Instantiate the generator in setup with a global var and give it the array we want to act on as the parameter.
let giveAPoint;
function setup() {
createCanvas(400, 200);
array1 = [2,4,6,8,10,12,14];
giveAPoint = loopOnArray(array1); // instantiate the generator with our array
}
Then in draw, ask at each round for a new point :
function draw(){
background(220);
frameRate(1);
strokeWeight(10);
stroke(255);
point(giveAPoint.next().value*20,100);
}
There is many advantages to externalize loops in a generator : no complicated indices or comparison in the draw loop , can easily limit to a fixed or variable number of rounds (by replacing while true) etc.
One more info: you can reuse as many time you want the generator function as long as you create new instances.