Quantcast
Channel: openFrameworks - Latest posts
Viewing all articles
Browse latest Browse all 40524

Using 'for' to loop a loop

$
0
0

I really recommend you to the read the references above, they are great! But I can give you a fun example.

So, arrays (and vectors, and other types of containers) are a way of storing information (numbers, characters, etc) for latter use.

In your previous example, you were assigning and using it right way. So a array wasn't exactly necessary. In this example, you'll store the latest 20 positions of the mouse, and use them to draw. Like a snake draw.

in ofApp.h

static const int numberOfCircles = 50;
ofVec2f mousePositions[numberOfCircles];

in setup()

ofBackground(0);

// Pump up the circle resolution for a smoother curve.
ofSetCircleResolution(44);

// Assign a starting value.
for (int i = 0; i < numberOfCircles ; ++i) {
    mousePositions[i] = ofVec2f(0,0);
}

At this point any position of the array returns a (0, 0) 2D vector. So, if you do something like:

 ofVec2f newVec = mousePositions[5];
 cout << newVec;

It would print '0, 0 ' to the console.


in update()

for (int i = 0; i < numberOfCircles - 1 ; ++i) {
        mousePositions[i] = mousePositions[i + 1];
}
mousePositions[numberOfCircles - 1] = ofVec2f(mouseX, mouseY);

Every cycle, you move the value of the array from one position to another. In this case, you move it down.
Note that I don't access the last element. That's why I did " i < numberOfCircle - 1 ".

So the value in the position 1, gets assigned to the position 0. The one from 2, gets assign to 1. And so on.

As an example, with you had a smaller array with {3, 6, 9, 2, 5, 1}.
Now you would have an array with {6, 9, 2, 5, 1, 1}.
The number 3 gets discarded.

If you noticed, you didn't touched the last position. That's because you want a new element on the last position: a new mouse position. So, after the loop, you assign a new mouse position to the last element.


in draw()

ofSetColor(255, 10);
    
// I added this nested loop to draw it 5 times, so that I can make a simple blur effect.
for (int i = 0; i < 5 ; ++i) {
    
    // Here I go through my array and draw the last 20 positions.
    for (int j = 0; j < numberOfCircles ; ++j) {
        ofCircle(mousePositions[j], 5 + j + i * 2);
    }
}

5 + j + i * 2 — this math is the trick.

First, I guarantee a minimum size of 5.
Then, by using the first iterator (i) multiplied by two, I can draw some bigger circles.
This, combined with the fact that I'm drawing with transparency (ofSetColor(255, 10)), I can do a simple blur fx.

At last, by also adding the second iterator (j), the older the mouse position, the smaller the circle.

I hope this enlightens you how containers work. Please, do mess around and have fun. Any questions, feel free to ask.


Viewing all articles
Browse latest Browse all 40524

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>