springForce.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* eslint-disable no-shadow */
  2. var test = require('tap').test;
  3. var dimensions = 2;
  4. var createSpringForce = require('../lib/codeGenerators/generateCreateSpringForce')(dimensions);
  5. var Body = require('../lib/codeGenerators/generateCreateBody')(dimensions);
  6. var Spring = require('../lib/spring');
  7. var random = require('ngraph.random')(42);
  8. test('Initialized with default value', function (t) {
  9. t.throws(() => createSpringForce());
  10. t.end();
  11. });
  12. test('Should bump bodies at same position', function (t) {
  13. var body1 = new Body(0, 0);
  14. var body2 = new Body(0, 0);
  15. // length between two bodies is 2, while ideal length is 1. Each body
  16. // should start moving towards each other after force update
  17. var idealLength = 1;
  18. var spring = new Spring(body1, body2, idealLength);
  19. var springForce = createSpringForce({springCoefficient: 0.1, springLength: 1}, random);
  20. springForce.update(spring);
  21. t.ok(body1.force.x > 0, 'Body 1 should go right');
  22. t.ok(body2.force.x < 0, 'Body 2 should go left');
  23. t.end();
  24. });
  25. test('Check spring force direction', function (t) {
  26. var springForce = createSpringForce({springCoefficient: 0.1, springLength: 1});
  27. t.test('Should contract two bodies when ideal length is smaller than actual', function (t) {
  28. var body1 = new Body(-1, 0);
  29. var body2 = new Body(+1, 0);
  30. // length between two bodies is 2, while ideal length is 1. Each body
  31. // should start moving towards each other after force update
  32. var idealLength = 1;
  33. var spring = new Spring(body1, body2, idealLength);
  34. springForce.update(spring);
  35. t.ok(body1.force.x > 0, 'Body 1 should go right');
  36. t.ok(body2.force.x < 0, 'Body 2 should go left');
  37. t.end();
  38. });
  39. t.test('Should repel two bodies when ideal length is larger than actual', function (t) {
  40. var body1 = new Body(-1, 0);
  41. var body2 = new Body(+1, 0);
  42. // length between two bodies is 2, while ideal length is 1. Each body
  43. // should start moving towards each other after force update
  44. var idealLength = 3;
  45. var spring = new Spring(body1, body2, idealLength);
  46. springForce.update(spring);
  47. t.ok(body1.force.x < 0, 'Body 1 should go left');
  48. t.ok(body2.force.x > 0, 'Body 2 should go right');
  49. t.end();
  50. });
  51. t.end();
  52. });