> codeonion / page

Sand Balance

Click or hold inside the box to pour sand onto the balance. Balance the iron weight to within 2% to win. Every level drops a random amount of sand per click (shown in the bottom bar). Press Reset for a new level.

Left torque: 0 Pour sand to balance the scale Right torque: 0
Click or hold inside the box to pour sand. Per click: 0 g. Grains: 0 / spilled: 0

Want to know how it works? Read the tutorial: Three.js Falling Sand: Build a Balance-the-Scale Physics Game.

Sand Balance // game logic flowchart
One frame: input changes state, fixed physics steps move the sand, torque tilts the beam, then three.js draws it. INPUT // STATE // LOOPClick or hold in the boxspawn(x, burst)10-50 g per click (random)matching rate while heldReset buttonreset(): new levelrandom iron weightrandom sand per clickShared stategrains[ ] beamBins[ ]floorBins[ ] anglerequestAnimationFrameAccumulatorrun fixed 1/60 s stepsclearsaddsstep(dt) // EVERY FREE GRAINGravity and movevy += g dt, x += v dtBounce off box wallstoLocal(): into beam spaceLanded onbeam pile?settleOnBeam()slide to a lower binPile tallerthan the lip?Stacked on beamadds weight to its sideHit floorpile?settleOnFloor()restingSpill over edgefree againyesnonoyesyesno: keep fallingfallsstep()readsBALANCE // HUD // DRAWTorquesum of mass x lever armleft side vs right sideTarget tilt-0.32 tanh(torque / 1500)Damped springsets beam.rotation.zAll settled andwithin 2 percent?BALANCED!Heavierside showndraw()positions to BufferGeometryTHREE.Pointsrenderer.render()after grainsyesnonext frame