So i tried to make the gravitation simulation in processing and it worked really well unti i tried to add more than 1 particle. here is my code:
PVector attract;
int count = 0;
particle par[] = new particle[100];
void setup(){
size(600,600);
background(0);
attract = new PVector();
noStroke();
for (int i = 0; i < 20; i++){ // change this 20 to 1 to see intended behavior
par[i] = new particle(0,-200,1);
count++;
}
noStroke();
}
void draw(){
background(0);
translate(width/2, height/2);
fill(0,255,0);
ellipse(attract.x,attract.y,20,20);
fill(255);
for (int i = 0; i < count; i++){
par[i].update();
par[i].show();
par[i].attraction(attract, 1);
}
}
void mousePressed(){
par[count] = new particle(0,-200,1);
count++;
}
And there is my particle class:
class particle {
float x, y;
float mass;
PVector pos;
PVector vel;
PVector acc;
particle(float x, float y, float mass) {
this.pos = new PVector(x, y);
this.mass = mass;
this.vel = PVector.random2D();
this.acc = new PVector();
}
void update() {
this.vel.add(this.acc);
this.pos.add(this.vel);
}
void show() {
fill(255);
noStroke();
ellipse(this.pos.x, this.pos.y, this.mass*5, this.mass*5);
}
void attraction(PVector target, float targetMass) {
PVector dir = target.sub(this.pos);
float disSq = dir.magSq();
disSq = con(disSq, 25, 500);
float G = 6.67408;
float magnitude = G*((this.mass*targetMass)/disSq);
dir.setMag(magnitude);
this.acc=dir;
}
PVector conVec(PVector val, float min, float max) {
if (val.x>max) val.x = max;
if (val.x<min) val.x = min;
if (val.y>max) val.y = max;
if (val.y<min) val.y = min;
return val;
}
float con(float val, float min, float max) {
if (val>max) val = max;
if (val<min) val = min;
return val;
}
}
I really don’t know what I’m doing wrong please someone help me.`