eulerIntegrator.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. var test = require('tap').test;
  2. var dimensions = 2;
  3. var Body = require('../lib/codeGenerators/generateCreateBody')(dimensions);
  4. var integrate = require('../lib/codeGenerators/generateIntegrator')(dimensions);
  5. test('Body preserves velocity without forces', function (t) {
  6. var body = new Body();
  7. var timeStep = 1;
  8. body.mass = 1; body.velocity.x = 1;
  9. integrate([body], timeStep);
  10. t.equal(body.pos.x, 1, 'Should move by 1 pixel on first iteration');
  11. timeStep = 2; // let's increase time step:
  12. integrate([body], timeStep);
  13. t.equal(body.pos.x, 3, 'Should move by 2 pixel on second iteration');
  14. t.end();
  15. });
  16. test('Body gains velocity under force', function (t) {
  17. var body = new Body();
  18. var timeStep = 1;
  19. body.mass = 1; body.force.x = 0.1;
  20. // F = m * a;
  21. // since mass = 1 => F = a = y';
  22. integrate([body], timeStep);
  23. t.equal(body.velocity.x, 0.1, 'Should increase velocity');
  24. integrate([body], timeStep);
  25. t.equal(body.velocity.x, 0.2, 'Should increase velocity');
  26. // floating point math:
  27. t.ok(0.29 < body.pos.x && body.pos.x < 0.31, 'Position should be at 0.3 now');
  28. t.end();
  29. });
  30. test('No bodies yield 0 movement', function (t) {
  31. var movement = integrate([], 2);
  32. t.equal(movement, 0, 'Nothing has moved');
  33. t.end();
  34. });
  35. test('Body does not move faster than 1px', function (t) {
  36. var body = new Body();
  37. var timeStep = 1;
  38. body.mass = 1; body.force.x = 2;
  39. integrate([body], timeStep);
  40. t.ok(body.velocity.x <= 1, 'Velocity should be within speed limit');
  41. integrate([body], timeStep);
  42. t.ok(body.velocity.x <= 1, 'Velocity should be within speed limit');
  43. t.end();
  44. });
  45. test('Can get total system movement', function (t) {
  46. var body = new Body();
  47. var timeStep = 1;
  48. body.mass = 1; body.velocity.x = 0.2;
  49. var movement = integrate([body], timeStep);
  50. // to improve performance, integrator does not take square root, thus
  51. // total movement is .2 * .2 = 0.04;
  52. t.ok(0.04 <= movement && movement <= 0.041, 'System should travel by 0.2 pixels');
  53. t.end();
  54. });