Limit chain preview to max link distance

This commit is contained in:
Daddy32
2025-12-12 19:32:42 +01:00
parent 3ea13ceaf9
commit c2535c6e65

36
main.js
View File

@@ -25,6 +25,7 @@
lineWidth: 3,
rope: true,
renderType: "line",
maxLengthMultiplier: 3.1,
},
};
@@ -45,6 +46,7 @@
lineWidth: 3,
rope: true,
renderType: "line",
maxLengthMultiplier: 3.2,
},
},
createBodies: (w, h) => [
@@ -91,6 +93,7 @@
lineWidth: 4,
rope: false,
renderType: "spring",
maxLengthMultiplier: 6.7,
},
},
createBodies: (w, h) => [
@@ -130,6 +133,7 @@
lineWidth: 3,
rope: false,
renderType: "line",
maxLengthMultiplier: 16.8,
},
},
createBodies: (w, h) => {
@@ -274,6 +278,15 @@
pointer: null,
};
const getMaxLinkDistance = () => {
const linkCfg = config.link || {};
if (Number.isFinite(linkCfg.maxLinkLength)) {
return linkCfg.maxLinkLength;
}
const mult = linkCfg.maxLengthMultiplier ?? 3;
return mult * config.ballRadius;
};
const spawnBall = () => {
if (gameOver) return;
const color =
@@ -516,6 +529,11 @@
return;
}
if (body.plugin.color !== chain.color) return;
const maxLinkDist = getMaxLinkDistance();
const dist = Vector.magnitude(
Vector.sub(chain.bodies[chain.bodies.length - 1].position, body.position),
);
if (dist > maxLinkDist) return;
addToChain(body);
};
@@ -644,13 +662,29 @@
if (!chain.active || !chain.pointer || chain.bodies.length === 0) return;
const last = chain.bodies[chain.bodies.length - 1];
const ctx = render.context;
const maxLinkDist = getMaxLinkDistance();
const delta = Vector.sub(chain.pointer, last.position);
const dist = Vector.magnitude(delta);
// Pull back the preview line slightly so it does not suggest a link will land on a too-distant ball.
const previewMargin = config.ballRadius;
const cappedDist = Math.max(
0,
Math.min(dist, Math.max(0, maxLinkDist - previewMargin)),
);
const safeTarget =
dist > 0
? Vector.add(
last.position,
Vector.mult(Vector.normalise(delta), cappedDist),
)
: chain.pointer;
ctx.save();
ctx.strokeStyle = chain.color || "#fff";
ctx.lineWidth = 3;
ctx.setLineDash([6, 6]);
ctx.beginPath();
ctx.moveTo(last.position.x, last.position.y);
ctx.lineTo(chain.pointer.x, chain.pointer.y);
ctx.lineTo(safeTarget.x, safeTarget.y);
ctx.stroke();
ctx.restore();
});