fix floating point issue in bezier

This commit is contained in:
2026-09-03 23:36:47 +02:00
parent f1205e3851
commit a04518fb0d
2 changed files with 18 additions and 16 deletions
+17 -15
View File
@@ -25,28 +25,30 @@ export function lerp(a: number, b: number, t: number) {
} }
export function quadraticBezier(a: Point, b: Point, c: Point, res=0.05) { export function quadraticBezier(a: Point, b: Point, c: Point, res=0.05) {
const eps = 0.001; // to prevent issues with float comparaison (p <= 1) const steps = Math.max(1, Math.ceil(1 / res))
const curve = []; const curve = [];
for (let p = 0; p - 1 < eps; p += res) { for (let i = 0; i <= steps; i++) {
const ab = lerpPoint(a, b, p); const p = i / steps;
const bc = lerpPoint(b, c, p); const ab = lerpPoint(a, b, p);
const abc = lerpPoint(ab, bc, p); const bc = lerpPoint(b, c, p);
curve.push(abc); const abc = lerpPoint(ab, bc, p);
curve.push(abc);
} }
return curve; return curve;
} }
export function cubicBezier(a: Point, b: Point, c: Point, d: Point, res=0.05) { export function cubicBezier(a: Point, b: Point, c: Point, d: Point, res=0.05) {
const eps = 0.001; // to prevent issues with float comparaison (p <= 1) const steps = Math.max(1, Math.ceil(1 / res))
const curve = []; const curve = [];
for (let p = 0; p - 1 < eps; p += res) { for (let i = 0; i <= steps; i++) {
const ab = lerpPoint(a, b, p); const p = i / steps;
const bc = lerpPoint(b, c, p); const ab = lerpPoint(a, b, p);
const cd = lerpPoint(c, d, p); const bc = lerpPoint(b, c, p);
const abc = lerpPoint(ab, bc, p); const cd = lerpPoint(c, d, p);
const bcd = lerpPoint(bc, cd, p); const abc = lerpPoint(ab, bc, p);
const abcd = lerpPoint(abc, bcd, p); const bcd = lerpPoint(bc, cd, p);
curve.push(abcd); const abcd = lerpPoint(abc, bcd, p);
curve.push(abcd);
} }
return curve; return curve;
} }
+1 -1
View File
@@ -84,7 +84,7 @@ function update(ctx: CanvasRenderingContext2D, time: number) {
if (lastTime == null) lastTime = time; if (lastTime == null) lastTime = time;
const dt = (time - lastTime) / 1000; // s const dt = (time - lastTime) / 1000; // s
lastTime = time; lastTime = time;
apple = apple as Vec2d; if (apple == null) return;
if (!paused) { if (!paused) {
// update head position // update head position