Guest User

Custom radial force

a guest
Jan 4th, 2019
505
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function customRadial(radius, x, y) {
  2.  
  3.   var constant = function(x) {
  4.     return function() {
  5.       return x;
  6.     };
  7.   };
  8.  
  9.   var nodes,
  10.     strength = constant(0.1),
  11.     strengths,
  12.     radiuses,
  13.     xs,
  14.     ys;
  15.  
  16.   if (typeof radius !== "function") radius = constant(+radius);
  17.   if (typeof x !== "function") x = constant(x == null ? 0 : +x);
  18.   if (typeof y !== "function") y = constant(y == null ? 0 : +y);
  19.  
  20.   function force(alpha) {
  21.     for (var i = 0, n = nodes.length; i < n; ++i) {
  22.       var node = nodes[i],
  23.         dx = node.x - xs[i] || 1e-6,
  24.         dy = node.y - ys[i] || 1e-6,
  25.         r = Math.sqrt(dx * dx + dy * dy),
  26.         k = (radiuses[i] - r) * strengths[i] * alpha / r;
  27.       node.vx += dx * k;
  28.       node.vy += dy * k;
  29.     }
  30.   }
  31.  
  32.   function initialize() {
  33.     if (!nodes) return;
  34.     var i, n = nodes.length;
  35.     strengths = new Array(n);
  36.     radiuses = new Array(n);
  37.     xs = new Array(n);
  38.     ys = new Array(n);
  39.     for (i = 0; i < n; ++i) {
  40.       radiuses[i] = +radius(nodes[i], i, nodes);
  41.       xs[i] = +x(nodes[i], i, nodes);
  42.       ys[i] = +y(nodes[i], i, nodes);
  43.       strengths[i] = isNaN(radiuses[i]) ? 0 : +strength(nodes[i], i, nodes);
  44.     }
  45.   }
  46.  
  47.   force.initialize = function(_) {
  48.     nodes = _, initialize();
  49.   };
  50.  
  51.   force.strength = function(_) {
  52.     return arguments.length ? (strength = typeof _ === "function" ? _ : constant(+_), initialize(), force) : strength;
  53.   };
  54.  
  55.   force.radius = function(_) {
  56.     return arguments.length ? (radius = typeof _ === "function" ? _ : constant(+_), initialize(), force) : radius;
  57.   };
  58.  
  59.   force.x = function(_) {
  60.     return arguments.length ? (x = typeof _ === "function" ? _ : constant(+_), initialize(), force) : x;
  61.   };
  62.  
  63.   force.y = function(_) {
  64.     return arguments.length ? (y = typeof _ === "function" ? _ : constant(+_), initialize(), force) : y;
  65.   };
  66.  
  67.   return force;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment