From 4ed6e2e050e0d9f3d2339bf27773a96d06300a98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Philippe=20Rivi=C3=A8re?= Date: Fri, 31 Mar 2023 11:13:17 +0200 Subject: [PATCH] fixes #199 --- src/collide.js | 14 +++++++++++--- test/collide-test.js | 5 ++--- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/collide.js b/src/collide.js index 8ebd8d9..36f4455 100644 --- a/src/collide.js +++ b/src/collide.js @@ -26,7 +26,9 @@ export default function(radius) { xi, yi, ri, - ri2; + ri2, + ax, + ay; for (var k = 0; k < iterations; ++k) { tree = quadtree(nodes, x, y).visitAfter(prepare); @@ -36,6 +38,12 @@ export default function(radius) { xi = node.x + node.vx; yi = node.y + node.vy; tree.visit(apply); + if (ax) { + node.x += ax; + node.y += ay; + ax = 0; + ay = 0; + } } } @@ -47,8 +55,8 @@ export default function(radius) { y = yi - data.y - data.vy, l = x * x + y * y; if (l < r * r) { - if (x === 0) x = jiggle(random), l += x * x; - if (y === 0) y = jiggle(random), l += y * y; + if (x === 0) ax = jiggle(random), l += ax * ax; + if (y === 0) ay = jiggle(random), l += ay * ay; l = (r - (l = Math.sqrt(l))) / l * strength; node.vx += (x *= l) * (r = (rj *= rj) / (ri2 + rj)); node.vy += (y *= l) * r; diff --git a/test/collide-test.js b/test/collide-test.js index 708196a..f9264be 100644 --- a/test/collide-test.js +++ b/test/collide-test.js @@ -39,12 +39,11 @@ it("forceCollide jiggles equal positions", () => { f.tick(); assert(a.x !== b.x); assert(a.y !== b.y); - assert.strictEqual(a.vx, -b.vx); - assert.strictEqual(a.vy, -b.vy); }); it("forceCollide jiggles in a reproducible way", () => { const nodes = Array.from({length:10}, () => ({x: 0, y: 0})); forceSimulation().nodes(nodes).force("collide", forceCollide()).stop().tick(50); - assertNodeEqual(nodes[0], {x: -5.371433857229194, y: -2.6644608278592576, index: 0, vy: 0, vx: 0}); + assertNodeEqual(nodes[0], {x: -4.0299664949858, y: -7.540553942916919, index: 0, vy: 0, vx: 0}); + assertNodeEqual(nodes[9], {x: 4.160131242078688, y: 0.2022776974891026, index: 9, vy: 0, vx: 0}); });