DEV Community

Aayush Shah
Aayush Shah

Posted on AI-assisted

I Accidentally Nudged My Stylus on My Desk and Ended Up Writing a Kinematics Simulator

As a high school student in India preparing for competitive STEM exams (JEE Advanced), you spend 12+ hours a day knee-deep in Newtonian mechanics, coordinate transformations, and differential equations.

When you solve kinematics problems for months on end, your brain starts projecting vectors, friction coefficients, and normal forces onto practically everything in your peripheral vision.

One evening, in the middle of a marathon problem-solving session, I placed my digital drawing stylus horizontally on my tablet surface.

I stretched, bumped my desk, and the pen began to roll back and forth on its slightly asymmetrical barrel. It rocked to and fro, steadily losing momentum until it settled to a dead stop.

I glanced up at my monitor and froze.

My cursor had been tracking this movement across the screen. Because the stylus was rocking with physical friction, the displacement on the monitor wasn't random mouse jitter—it was a textbook, real-world demonstration of Damped Simple Harmonic Motion (SHM) unfolding in front of me.

Instead of getting back to my problem set, I opened VS Code.


The Underlying Physics: Modeling the Desk

In classical mechanics, damped harmonic motion is described by a second-order linear differential equation:

md2xdt2+bdxdt+kx=0 m \frac{d^2x}{dt^2} + b \frac{dx}{dt} + kx = 0

When mechanical damping is small (the underdamped regime), the exact position as a function of time describes an oscillation confined inside an exponentially decaying envelope:

x(t)=Ae−γtcos⁡(ωt+ϕ) x(t) = A e^{-\gamma t} \cos(\omega t + \phi)

Where:

  • AA is the initial displacement amplitude in pixels.
  • γ\gamma is the damping factor (the friction between the pen and the desk).
  • ω\omega is the angular frequency determined by the stylus barrel curvature.
  • ϕ\phi is the initial phase angle offset.

I wanted to build a web tool— Pendula — that could take raw human cursor movement, fit it to this exact differential equation, and calculate the physical friction coefficient of whatever object was rolling on your desk.


Engineering the Live Tracker: Turning Jitter into Curves

Browser mouse events provide raw pixel integers via (e.clientX,e.clientY)(e.clientX, e.clientY) . Transforming noisy human motion into a clean theoretical model in real time required three steps:

1. 1D Dimensionality Reduction (PCA)

A rolling stylus moves along a single axis, but human hands rarely orient it perfectly horizontal or vertical. Using Principal Component Analysis (PCA) on a rolling buffer of mouse samples, the engine automatically extracts the primary axis of motion and projects 2D coordinates onto a normalized 1D displacement axis x(t)x(t) .

2. Peak & Period Extraction

The engine registers local displacement peaks xmaxx_{\text{max}} across time to calculate the empirical oscillation period:

T=2πω T = \frac{2\pi}{\omega}

3. Curve Fitting via Simulated Annealing

Because human input has hand jitter and surface imperfections, fitting the data using standard gradient descent gets trapped in local minima.

Instead, Pendula runs an optimization loop using simulated annealing: it iteratively perturbs the theoretical parameters (A,γ,ω,ϕ)(A, \gamma, \omega, \phi) to minimize the Mean Squared Error:

MSE=1N∑i=1N(xobserved(ti)−xtheoretical(ti))2 \text{MSE} = \frac{1}{N} \sum_{i=1}^{N} \Big( x_{\text{observed}}(t_i) - x_{\text{theoretical}}(t_i) \Big)^2

Once settled, a live overlay displays the race: your raw blue cursor trail plotted side-by-side against the ideal orange mathematical curve.


🕵️ The Twist: Cheating My Own Math with JEE Physics

Once the first version was running with 95%+ accuracy on real pens, a devious thought struck me.

In JEE physics, one of the foundational geometric proofs you learn is that Simple Harmonic Motion is simply the 1D shadow of Uniform Circular Motion.

Knowing that Pendula projects 2D motion onto a 1D PCA axis, I realized I didn't actually need a rolling pen to get a 99% score. I could mathematically exploit my own optimizer with mouse gestures.

Here are the three exploits I used to break my own app:

1. The Inward Spiral (90%+ Fit Score)

If you draw a continuous spiral inward with your mouse, you are tracing a decaying polar curve:

r(t)=Ae−γt r(t) = A e^{-\gamma t}

When the PCA projects this 2D spiral onto its 1D primary axis, the coordinate becomes:

x(t)=r(t)cos⁡(ωt)=Ae−γtcos⁡(ωt) x(t) = r(t) \cos(\omega t) = A e^{-\gamma t} \cos(\omega t)

This is literally the exact equation for Damped SHM! The 1D projection of a shrinking circle perfectly mimics a physical pendulum, and the optimizer awarded it a near-perfect score.

2. The Figure-8 Lissajous Curve (88%+ Score)

Drawing a decaying figure-8 creates a periodic, Lissajous-like oscillation. The 1D projection is noisy but repetitive enough to trap the Simulated Annealing engine in a high-scoring local minimum.

3. The Single Straight Swipe (99% Score)

The most blatant loophole: if you swipe your mouse in a straight line and brake to a stop, the optimizer sets frequency ω→0\omega \to 0 . The equation collapses into pure exponential decay:

x(t)=Ae−γt x(t) = A e^{-\gamma t}

The math engine saw zero oscillation and confidently declared the straight line to be a 99% perfect physical dampening!


🛡️ The Anti-Cheat Fix: Geometric Tripwires

To keep the simulator honest, I built a two-part validation tripwire into the post-analysis engine:

  1. Orthogonal Variance Guard: The engine now continuously measures displacement along the minor (perpendicular) PCA axis. If your perpendicular spread exceeds 15% of the primary axis, Pendula catches you drawing 2D shapes (spirals or figure-8s) and rejects the run.
  2. Path-to-Displacement Ratio: A real pendulum swings over the exact same territory multiple times—meaning total cumulative path length must be several times larger than the net spatial spread (Lpath≫Δxmax)(L_{\text{path}} \gg \Delta x_{\text{max}}) . If the total distance traveled roughly equals the displacement, Pendula flags the run as a single straight swipe.

Play With It Live

You can test both the physics engine and the cheat detection right in your browser—no downloads or setup needed:

(Tip: Open the pre-loaded .motion files in the app's Cheats menu to watch the anti-cheat system catch these mathematical loopholes in real time.)

Building software from first principles reminds me why I fell in love with both programming and physics: formulas on paper are great, but there's nothing quite like watching raw physical reality and code meet on screen.

Let me know your thoughts, and if you manage to find another mathematical loophole to break the engine, I’d love to hear it in the comments!

Top comments (0)