#### Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

# How to repel points and let them return to their initial state with forces?

Hi all,

I want to make a grid of particles where each particle gets attracted to it's initial position. Then I want to repel these particles with the position of my mouse. When I leave my mouse out of the area, the particles will return to their initial state.

Tagged:

• edited April 2017 Answer ✓
``````class particle{
float posx, posy, xinit, yinit;
float speedx, speedy;
particle(float X, float Y) {
posx=xinit=X;
posy=yinit=Y;
}
void home(){
chase(xinit,yinit,1);
}
void chase(float mx,float my,float force){
float dx=(posx-mx);
float dy=(posy-my);
force/=(dx*dx+dy*dy);
if (abs(dx)<1&&abs(dy)<1){
speedx=speedy=force=0;
} else{
speedx-=(dx*force);
speedy-=(dy*force);
}
}
void show(){
speedx*=0.99;
speedy*=0.99;
posx+=speedx;
posy+=speedy;
posx=constrain(posx,0,200);
posy=constrain(posy,0,200);
point(posx,posy);
}
}
boolean chase;
particle [] parts;
void setup(){
size(400,400);
strokeWeight(3);
parts = new particle[100];
for(int i=0; i<100; i++){
parts[i]=new particle((i*20)%200,i/10*20);
}
}
void draw(){
background(255);
chase = (mouseX<200 && mouseY<200);
for(int i=0; i<100; i++){
if(chase){parts[i].chase(mouseX,mouseY,1);}
else {parts[i].home();}
parts[i].show();
}
}
``````
• Thanks! I also looked into some of the older video's of Dan Shiffman where he explains more about steering and arriving behaviour. Going to look into that too ;)

• edited April 2017

For a non-particle-based immediate rendering of this mouse-repels-points effect, you could also modify the Processing Distance2D or Array2D examples

Here is an example using PVector:

``````float max_distance, scale;
PVector v, v2, vdiff;

void setup() {
size(640, 360);
noStroke();
max_distance = 150;
scale = 0.33;
}

void draw() {
background(0);
for(int i = 0; i <= width; i += 20) {
for(int j = 0; j <= height; j += 20) {
v = new PVector(i,j);
v2 = new PVector(mouseX, mouseY);
if(PVector.dist(v,v2)<max_distance){
vdiff = PVector.sub(v,v2);
vdiff.setMag((max_distance - vdiff.mag()) * scale);
}
ellipse(v.x, v.y, 10, 10);
}
}

// pulse the max distance and scaling factors
max_distance = sin(PI*(millis()%5000)/5000)*300;
scale = sin(PI*(millis()%3333)/3333)*0.75;
}
``````

...although i believe you could also achieve this effect using arctangent:

Note however that this rendering is immediate and almost based on the latest mouse position -- making these dots displace in messy ways or "drift back" might be quite complex compared to the particle-based approach.