Advertisement
bildramer

Untitled

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