Calculating Gravity

closed account (2NywAqkS)
So far I have a particle simulator that puts 10000 particles randomly dotted around the screen and I want them to move towards a gravitational centre (0, 0). Assuming x and y is the particle's position how do I correctly move it towards (0 ,0) simulating gravity.

Thanks Rowan.
You have to do the calculation on each particle individually.

If you make a class representing the particles, then stick the particles in an array, you can use the same code over and over with a for loop.

example:
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
double massOfOrigin = 10000.0;
const double G = 6.67384e-11;

class particle
{
public: 
    void get_accelleration(double &acc_x, double &acc_y);
    particle();
private: 
    double mass
    double x;
    double y;
}

//CTOR
particle::particle()
{
    x = (double)(rand() % 10000);
    y = (double)(rand() % 10000);
    mass = (double)(rand()%100);
}

void particle::get_accelleration(double &acc_x, double &acc_y)
{
    double r = sqrt(x*x + y*y); // F = G * (m1 * m2)/(r^2), a = G * m2/(r^2);
    acc_x = G * massOfOrigin / (r * cos(x/r));
    acc_y = G * massOfOrigin / (r * sin(y/r));
}

int main()
{
    vector<particle> vparticles;
    for (int i = 0; i < 10000; i++)
        vparticles.push_back(particle());

    //I'm goign to bed now, but you can calculate the new positions of each particle here. 
    // Use their accellerations in x and y to calculate the new position each iteration.
    // use a sleep or something in a while loop to simulate time steps.
}
Last edited on
closed account (2NywAqkS)
Thanks very helpful. I had already set up a data array and loop but using a much more primitive method so in the morning I will try out this.
Topic archived. No new replies allowed.