# Shifting positions of circles based on mouse position

So I managed to create a 2d array to position a bunch of circles randomly on the screen…

Here’s what’s on the .h file:

``````    ofPoint positions;
``````

Here’s what’s on the .cpp file:

``````void ofApp::setup(){
for (int i = 0; i < 100; i++){
for (int j = 0; j < 100; j++){
positions[i][j] = ofPoint(i*10 + ofRandom(-7,7),  j*10 + ofRandom(-7,7));
}
}
}

void ofApp::draw(){
for (int i = 0; i < 100; i++){
for (int j = 0; j < 100; j++){
ofDrawCircle(positions[i][j], 3);
}
}
``````

So if I want the circles on the screen to “move out of the way” on the spot where I click my mouse, what would be the best way to do this? So essentially I need to find where my mouse position is when it’s pressed, and I need the circles located within say… 50px radius where my mouse has been clicked to shift their x,y position away from the mouseX and mouseY.

What’s the best way to do this?

First consider using a vector of objects like:

vector < ofPoint > positions;
or
vector < ofVec2f > positions;
or even:
vector < ofVec3f > circles; -> here you can randomly set a radius of circle

Here is a nice tutorial about vectors:
http://openframeworks.cc/ofBook/chapters/stl_vector.html

And next, check a distance of each circle on mousePressed or mouseReleased event and update a position when its true. You can iterate over the vector of circles:

for(int i=0;circles.size(),i++) {
if (abs(ofDist(mouseX, mousey, circles[i].x, circles[i].y)) < radius50px);
circles[i].x = something;
circles[i].y = something;

Another scenario is setting a flag on mouse Event and remember last clicked position and then update positions on update() and make movement slower.

1 Like

I know you are in my class and so don’t know about vectors yet here’s a simple approach – in ofApp mouse pressed you could do:

`````` void ofApp::mousePressed(int x, int y, int button){
for (int i = 0; i < 100; i++){
for (int j = 0; j < 100; j++){
float distance = ofDist(positions[i][j].x, positions[i][j].y, mouseX, mouseY);
if (distance < 50){
positions[i][j].x += ofRandom(-20,20);
positions[i][j].y += ofRandom(-20,20);
}
}
}
}
``````

that just adds a random amount for ones that are closed to the mouse but I can show you how to make it move away from the mouse if you’d like…

2 Likes

Oh great, thanks everyone!
I will check out more about vectors, but I was hoping to use ofDist somehow to do this, and @zach suggestion totally works! https://www.dropbox.com/s/vp46w5vg1non0zj/DailySketch09.mov?dl=0

Hi Zach! Practicing using the forum in anticipation of the class ending… but I guess you’ll still be the one answering my questions anyways 