1 | function clamp(v, min, max) {
|
---|
2 | return Math.max(min, Math.min(v, max));
|
---|
3 | }
|
---|
4 | const V = {
|
---|
5 | toVector(v, fallback) {
|
---|
6 | if (v === undefined) v = fallback;
|
---|
7 | return Array.isArray(v) ? v : [v, v];
|
---|
8 | },
|
---|
9 | add(v1, v2) {
|
---|
10 | return [v1[0] + v2[0], v1[1] + v2[1]];
|
---|
11 | },
|
---|
12 | sub(v1, v2) {
|
---|
13 | return [v1[0] - v2[0], v1[1] - v2[1]];
|
---|
14 | },
|
---|
15 | addTo(v1, v2) {
|
---|
16 | v1[0] += v2[0];
|
---|
17 | v1[1] += v2[1];
|
---|
18 | },
|
---|
19 | subTo(v1, v2) {
|
---|
20 | v1[0] -= v2[0];
|
---|
21 | v1[1] -= v2[1];
|
---|
22 | }
|
---|
23 | };
|
---|
24 | function rubberband(distance, dimension, constant) {
|
---|
25 | if (dimension === 0 || Math.abs(dimension) === Infinity) return Math.pow(distance, constant * 5);
|
---|
26 | return distance * dimension * constant / (dimension + constant * distance);
|
---|
27 | }
|
---|
28 | function rubberbandIfOutOfBounds(position, min, max, constant = 0.15) {
|
---|
29 | if (constant === 0) return clamp(position, min, max);
|
---|
30 | if (position < min) return -rubberband(min - position, max - min, constant) + min;
|
---|
31 | if (position > max) return +rubberband(position - max, max - min, constant) + max;
|
---|
32 | return position;
|
---|
33 | }
|
---|
34 | function computeRubberband(bounds, [Vx, Vy], [Rx, Ry]) {
|
---|
35 | const [[X0, X1], [Y0, Y1]] = bounds;
|
---|
36 | return [rubberbandIfOutOfBounds(Vx, X0, X1, Rx), rubberbandIfOutOfBounds(Vy, Y0, Y1, Ry)];
|
---|
37 | }
|
---|
38 |
|
---|
39 | export { V, computeRubberband as c, rubberbandIfOutOfBounds as r };
|
---|