vis.js is a dynamic, browser-based visualization library
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1022 B

  1. class CentralGravitySolver {
  2. constructor(body, physicsBody, options) {
  3. this.body = body;
  4. this.physicsBody = physicsBody;
  5. this.setOptions(options);
  6. }
  7. setOptions(options) {
  8. this.options = options;
  9. }
  10. solve() {
  11. let dx, dy, distance, node;
  12. let nodes = this.body.nodes;
  13. let nodeIndices = this.physicsBody.physicsNodeIndices;
  14. let forces = this.physicsBody.forces;
  15. for (let i = 0; i < nodeIndices.length; i++) {
  16. let nodeId = nodeIndices[i];
  17. node = nodes[nodeId];
  18. dx = -node.x;
  19. dy = -node.y;
  20. distance = Math.sqrt(dx * dx + dy * dy);
  21. this._calculateForces(distance, dx, dy, forces, node);
  22. }
  23. }
  24. /**
  25. * Calculate the forces based on the distance.
  26. * @private
  27. */
  28. _calculateForces(distance, dx, dy, forces, node) {
  29. let gravityForce = (distance === 0) ? 0 : (this.options.centralGravity / distance);
  30. forces[node.id].x = dx * gravityForce;
  31. forces[node.id].y = dy * gravityForce;
  32. }
  33. }
  34. export default CentralGravitySolver;