-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathforceAttract.js
72 lines (55 loc) · 1.6 KB
/
forceAttract.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* Pulls nodes toward a specified `(x, y)` target point.
*/
export default function (target) {
let nodes,
targets,
strength,
strengths;
function force (alpha) {
let node, target, strength;
for (let i=0; i<nodes.length; i++) {
node = nodes[i];
target = targets[i];
strength = strengths[i];
node.vx += (target[0] - node.x) * strength * alpha;
node.vy += (target[1] - node.y) * strength * alpha;
}
}
function initialize () {
if (!nodes) return;
// populate local `strengths` using `strength` accessor
strengths = new Array(nodes.length);
for (let i=0; i<nodes.length; i++) strengths[i] = strength(nodes[i], i, nodes);
// populate local `targets` using `target` accessor
targets = new Array(nodes.length);
for (let i=0; i<nodes.length; i++) targets[i] = target(nodes[i], i, nodes);
}
force.initialize = _ => {
nodes = _;
initialize();
};
force.strength = _ => {
// return existing value if no value passed
if (_ == null) return strength;
// coerce `strength` accessor into a function
strength = typeof _ === 'function' ? _ : () => +_;
// reinitialize
initialize();
// allow chaining
return force;
};
force.target = _ => {
// return existing value if no value passed
if (_ == null) return target;
// coerce `target` accessor into a function
target = typeof _ === 'function' ? _ : () => _;
// reinitialize
initialize();
// allow chaining
return force;
};
if (!strength) force.strength(0.1);
if (!target) force.target([ 0, 0 ]);
return force;
}