HolonBody.java 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package classes;
  2. import java.awt.Color;
  3. public class HolonBody {
  4. private static final double G = 6.673e-11; // gravitational constant
  5. public int rx, ry; // holds the cartesian positions
  6. public double vx, vy; // velocity components
  7. public double fx, fy; // force components
  8. public double mass; // mass
  9. public Color color; // color
  10. // create and initialize a new Body
  11. public HolonBody(int rx, int ry, double vx, double vy, double mass, Color color) {
  12. this.rx = rx;
  13. this.ry = ry;
  14. this.vx = vx;
  15. this.vy = vy;
  16. this.mass = mass;
  17. this.color = color;
  18. }
  19. // update the velocity and position using a timestep dt
  20. public void update(double dt) {
  21. vx += dt * fx / mass;
  22. vy += dt * fy / mass;
  23. rx += dt * vx;
  24. ry += dt * vy;
  25. }
  26. // returns the distance between two bodies
  27. public double distanceTo(HolonBody b) {
  28. double dx = rx - b.rx;
  29. double dy = ry - b.ry;
  30. return Math.sqrt(dx*dx + dy*dy);
  31. }
  32. // set the force to 0 for the next iteration
  33. public void resetForce() {
  34. fx = 0.0;
  35. fy = 0.0;
  36. }
  37. // compute the net force acting between the body a and b, and
  38. // add to the net force acting on a
  39. public void addForce(HolonBody b) {
  40. HolonBody a = this;
  41. double EPS = 3E4; // softening parameter (just to avoid infinities)
  42. double dx = b.rx - a.rx;
  43. double dy = b.ry - a.ry;
  44. double dist = Math.sqrt(dx*dx + dy*dy);
  45. double F = (G * a.mass * b.mass) / (dist*dist + EPS*EPS);
  46. a.fx += F * dx / dist;
  47. a.fy += F * dy / dist;
  48. }
  49. // convert to string representation formatted nicely
  50. public String toString() {
  51. return "" + rx + ", "+ ry+ ", "+ vx+ ", "+ vy+ ", "+ mass;
  52. }
  53. }