-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gravity.pde
111 lines (86 loc) · 2.38 KB
/
Gravity.pde
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
Particle[] planets = new Particle[100];
float[] randomX = new float[100];
float[] randomY = new float[100];
float gravConstScale = 0.6;
class Particle {
PVector displacement;
PVector velocity;
PVector acceleration;
float mass;
Particle (float mass, float x, float y) {
this.mass = mass;
this.displacement = new PVector(x, y);
this.velocity = new PVector(0, 0);
this.acceleration = new PVector(0, 0);
}
void applyForce(PVector force) {
PVector f = force.get();
f.div(mass);
acceleration.add(f);
}
PVector attract(Particle object) {
PVector force = PVector.sub(this.displacement, object.displacement);
float distance = force.mag();
distance = constrain(distance, 5.0, 45.0);
force.normalize();
float mag = ( gravConstScale * this.mass * object.mass) / (distance * distance);
force.mult(mag);
return force;
}
void checkEdges() {
if (displacement.x > width) {
displacement.x = width;
velocity.x *= -1;
} else if (displacement.x < 0) {
velocity.x *= -1;
displacement.x = 0;
}
if (displacement.y > height) {
velocity.y *= -1;
displacement.y = height;
} else if (displacement.y < 0) {
velocity.y *= -1;
displacement.y = 0;
}
}
void update() {
velocity.add(acceleration);
displacement.add(velocity);
acceleration.mult(0);
}
void display() {
stroke(0);
fill(175);
ellipse(displacement.x, displacement.y,mass*10,mass*10);
}
}
void setup() {
size(400, 400);
for (int i = 0; i < planets.length; i++) {
planets[i] = new Particle(random(0.1, 2), random(width), random(height));
}
for (int i = 0; i < randomX.length; i++) {
randomX[i] = random(width);
}
for (int i = 0; i < randomY.length; i++) {
randomY[i] = random(height);
}
}
void draw() {
background(0);
for (int i = 0; i < 100; i++) {
fill(255);
rect(randomX[i], randomY[i], 3, 3);
}
for (int i = 0; i < planets.length; i++) {
for(int j = 0; j < planets.length; j++) {
if (i != j) {
PVector gravForce = planets[j].attract(planets[i]);
planets[i].applyForce(gravForce);
}
}
//planets[i].checkEdges();
planets[i].update();
planets[i].display();
}
}