utilities.js 997 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. function pt(x,y) {
  2. return {x: x, y: y};
  3. }
  4. function ptc(p) {
  5. return {x: p.x, y: p.y};
  6. }
  7. // return the lengt hof a vector
  8. function magnitude(p) {
  9. return Math.sqrt(p.x * p.x + p.y * p.y); // basic pythagorean theorem: a^2 + b^2 = c^2
  10. }
  11. // return a vector in the same direction with a magnitude (length) of 1.0
  12. function normalize(p) {
  13. var l = Math.sqrt(p.x * p.x + p.y * p.y);
  14. if(l == 0) return {x: 0, y: 0}; // avoid divide-by-zero
  15. return {x: p.x / l, y: p.y / l};
  16. }
  17. function rect(top, left, bottom, right) {
  18. return {t: top, b: bottom, l: left, r: right};
  19. }
  20. function rectc(r) {
  21. return {t: r.t, b: r.b, l: r.l, r: r.r};
  22. }
  23. function distance(from, to) {
  24. var x = to.x - from.x;
  25. var y = to.y - from.y;
  26. return Math.sqrt(x*x + y*y);
  27. }
  28. /*
  29. varies between 0 and 1 with a quick rise and slow fall
  30. k determines how long the impulse is
  31. t is the time along the curve to return
  32. the peak, 1.0, is at t = 1 / k
  33. */
  34. function impulse(k, t) {
  35. var h = k * t;
  36. return h * Math.exp(1.0 - h);
  37. }