Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //simple gravity sim
- //fun fact: electric forces work similarly, just swap the +=/-=, change mass to charge and divide by the particles' own mass
- //this is not-quite-pseudocode, you have to refit it and write some boilerplate
- //so no cheap India IT copypasting pls
- const double friction = 0.002;
- const double gravity = 1.0;
- //^ magnitudes for forces
- for(int i = 0;i < PLANETS - 1;i++) { //these loops will go over all pairs where i < j
- for(int j = i + 1;j < PLANETS;j++) {
- vector d = planets[j].pos - planets[i].pos; //you need some kind of vector class, obviously
- planets[i].vel += d * gravity * timestep * planets[j].mass / (sqrt(d.x*d.x+d.y*d.y)*(d.x*d.x+d.y*d.y));
- planets[j].vel -= d * gravity * timestep * planets[i].mass / (sqrt(d.x*d.x+d.y*d.y)*(d.x*d.x+d.y*d.y));
- /*look at that mess
- explanation for timestep is below
- gravitational force = g * m1 * m2 / r^2
- because F = m * a we can ignore the particle's own mass
- d.x*d.x+d.y*d.y is equal to the squared magnitude of d, which is a scalar
- but we need a vector, so we multiply by d first, so we have to divide by |d|^3 instead
- btw: be wary of division by zero here
- */
- }
- }
- for(int i = 0;i < PLANETS;i++) {
- planets[i].pos += planets[i].vel * timestep;
- /*timestep is the amount of time that passes each step
- it can vary if you need variable FPS, but keep in mind
- that simulation accuracy strongly depends on it
- this is Eulerian integration: for fancier methods, look up Verlet or Runge-Kutta
- here, the velocity is multiplied by the square of the timestep
- normally you'd multiply the acceleration once and the velocity once,
- but this will speed up things by at least 0.005%
- */
- planets[i].vel *= pow(1.0 - friction, timestep); //friction, disable if you want long-term simulations to end up horribly inaccurate
- }
- //and there you have it
- //this is easily extendable to 3D or spring forces or whatever you like, too, if you know the (really simple) math
- //have fun
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement