Skip to content
Source
Sign inSign up
samwillis/neonbricks
Open History to see the last commit

cursor-motion.ts

61 lines2.0 KB

1import { MathUtils, Vector3 } from "three";
2​
3// A critically damped spring keeps velocity continuous when a new packet
4// arrives. Its response follows the observed cadence instead of stopping
5// between sparsely delivered cursor samples.
6export class CursorMotion {
7 readonly position: Vector3;
8 readonly velocity = new Vector3();
9 private readonly target: Vector3;
10 private cadence = 0.25;
11 private lastArrival: number | null = null;
12​
13 constructor(point: Vector3) {
14 this.position = point.clone();
15 this.target = point.clone();
16 }
17​
18 receive(point: Vector3, arrivedAt: number) {
19 if (this.target.equals(point)) {
20 // Stationary presence refreshes do not describe a movement cadence.
21 this.lastArrival = null;
22 return;
23 }
24 if (this.lastArrival !== null) {
25 const gap = (arrivedAt - this.lastArrival) / 1000;
26 if (gap >= 0.08 && gap < 1.2)
27 this.cadence = MathUtils.lerp(
28 this.cadence,
29 MathUtils.clamp(gap, 0.12, 0.65),
30 0.4,
31 );
32 }
33 this.lastArrival = arrivedAt;
34 this.target.copy(point);
35 }
36​
37 advance(delta: number) {
38 if (delta <= 0) return;
39 if (delta > 0.5) {
40 // Resume at the current target after a backgrounded frame.
41 this.position.copy(this.target);
42 this.velocity.set(0, 0, 0);
43 return;
44 }
45 const omega = 2 / MathUtils.clamp(this.cadence * 1.1, 0.18, 0.6);
46 const decay = Math.exp(-omega * delta);
47 for (const axis of ["x", "y", "z"] as const) {
48 const offset = this.position[axis] - this.target[axis];
49 const rate = this.velocity[axis] + omega * offset;
50 const nextOffset = (offset + rate * delta) * decay;
51 this.velocity[axis] =
52 (this.velocity[axis] - omega * rate * delta) * decay;
53 this.position[axis] = this.target[axis] + nextOffset;
54 // Stop at the actual surface point rather than overshooting it.
55 if (offset * nextOffset < 0) {
56 this.position[axis] = this.target[axis];
57 this.velocity[axis] = 0;
58 }
59 }
60 }