Sergio’s Room v0.2 — grab, turn, drag and drop: a room with no buttons (a state machine, springs and a page that curls)
This project started as a 3D desk. Today it is “Sergio’s Room”, a story-driven game set in my room; this post tells how it started.
The first thing I did when I opened version 0.2 was to open the drawer and grab a folder. I pulled the handle, the drawer slid out with its weight, went a little too far and came back; I took out the Python folder, carried it to the desk and it opened by itself. Not a single button on screen. That is what v0.1 was missing, and this chapter tells how it is done, with all the code explained line by line. As in the previous version, the idea and the decisions are mine and the code is Claude’s, Anthropic’s AI; at the end I tell you how we worked on this version.
Sergio’s Room series · chapter 3 of 11. You are coming from chapter 2: the 3D prototype. The whole project is in the Sergio’s Room report.
In short
In version 0.2 the room is used with your hands. You grab an object with a click and it comes to your hand, where you can turn it to look at it from every side; the E key uses it and Esc puts it back. If you hold the button down and drag, you carry it across the desk: near the place where it fits, that place glows coral and, when you let go, it slots in by itself with its animation.
The discs are the mock exams and go into the disc drive; the USB sticks are the simulators and go into the tower’s port; the folders come out of the drawer; the books open in front of you and their pages curl as you turn them; the whiteboard is written on with a marker; the steam from the mug is Sergio Bot. And if you turn all the way round, behind you there is the door back to the website.
Table of Contents
What it had to achieve
Remove every button from v0.1 and give everything its own animation: the disc dropping into the tray, the page curling, the marker writing, the drawer with weight. The requirements were written at the start and ticked off at the end; “test” means an automated script that moves the mouse, takes pictures and writes to the console which state the program is in.
| Requirement | How it is checked | Met? |
|---|---|---|
| A current Three.js as a module, with a fixed version | Loads with no errors in the test | Yes: 0.186.1 |
| No buttons or interface text visible outside the PC | Screenshots of every mode | Yes |
| A dot instead of the cursor, which changes shape with the action | Screenshots with hand, fist, turn, marker, page and link | Yes |
| Grab, drag and drop: the zone glows as you get close and the object slots in | Test: state ocupado when dropping and monitor afterwards | Yes |
| Discs into the drive (mock exams) and USB sticks into the port (simulators) | Tests: the monitor shows the mock exam and the simulator | Yes |
| Inspect mode: click grabs, drag turns, wheel brings closer, E uses, Esc puts back | Test: state inspeccion and the book turned in the screenshot | Yes |
| Folders that come out of the drawer and open on the desk | Test: state carpeta | Yes |
| Pages that curl and stay on the left | Screenshot halfway through; the page does not stretch (script) | Yes |
| Whiteboard with marker, eraser and a T/F answer written stroke by stroke | Test: free stroke, F written and explanation | Yes |
| A mug with Sergio Bot in the steam | Test: state bot and an answer in the steam | Yes, with sample answers |
| Drawer with weight, lamp switch, steam and dust in the light | Screenshots; the drawer is a spring | Yes |
| Esc always goes one step back | Every mode goes back to libre with Esc | Yes |
A manual on the shelf and LEEME.txt on the PC | Screenshot of the open manual | Yes |
| Tab goes through the objects, Enter grabs, E uses; announcements for screen readers | Keyboard test | Yes |
| “Reduce motion”: nothing moves by itself | Two screenshots at rest: 0 pixels different | Yes |
| Outside the PC, everything is physical, no terminal commands | Review of spines, labels, whiteboard and poster | Yes |
| Full turn and a door back to the website | Test: heading π and the door ajar | Yes |
| A way for the recording scripts to aim at the objects | The scripts aim with it | Yes |
| No console errors | The tests print the errors | Yes |
| The website’s palette and fonts; code without ligatures | CSS review | Yes |
Design before code
My decisions at the start
Before programming, Claude asked me a single round of questions, and I answered more than I was asked:
- The mug opens Sergio Bot in the steam.
- The whiteboard has free drawing with a marker and a guided answer (you tap T or F and the marker writes it), in the Caveat font.
- The discs go in a case that opens as you get close and the USB sticks in a pen pot, so the desk does not fill up.
- An inspect mode like in Resident Evil: the object comes to your hand, you turn it by dragging and its action is on a key.
- Outside the PC, everything is physical: no terminal commands on books, folders or the whiteboard. The terminal belongs only to the computer.
- The camera turns all the way round and behind you is the door, the way out to the website.
The Resident Evil part has a reason: I thought of the remakes because I remembered that mechanic of inspecting objects. And when I talked about games where you “grab things”, I was thinking of those mystery games where, when you inspect an object, you find clues, codes… That is what I wanted for the room: objects that hide details.
The new floor plan
Compare it with the v0.1 plan. There are three new things: the disc case and the pen pot on the desk, the green plane where objects are dragged (at 0.765 m, slightly above the desktop) and the door, on a back wall that was moved out to 1.25 m from the chair so that it could be seen whole when you turn round.
One single gesture system
The most important drawing of this version was made before writing a single line: what each gesture means at each moment. A click does not do the same thing when your hand is empty as when you are inspecting a book. That is a state machine: the program is always in one state and each gesture takes it to another.
Follow a path with your finger: in FREE you move the mouse over a book (OVER: it glows), you press (PRESSED), and if you let go without moving it is a click: INSPECTING. If instead you move more than 6 pixels with the button held down, you go to CARRYING. Same fingers, two results. And leaving is always the same: Esc goes one step back.
The disc’s journey
Each object also has its own states. Some from the design table:
| Object | States | Gesture → animation |
|---|---|---|
| Disc case | closed · open | Pointer over it → the lid lifts with a bounce |
| Disc | in the case · in your hand · carried · in the tray · inside | Near the tower → the tray slides out and glows · drop → it falls with a bounce and goes in |
| Drawer | closed · open | Click → it opens on a spring · drag the handle → it follows with its weight |
| Book | on the shelf · in your hand · open | E → it opens in front of you · drag the page → it curls and stays on the left |
| Door | closed · ajar | Click → it opens a crack with light from the hallway · click on the light → the normal website |
Discarded ideas
| Idea | Why not |
|---|---|
| Discs and USB sticks loose on the desk, as in v0.1 | With four mock exams and four simulators, the desk filled up |
| Making the click perform the action directly | You miss the details; I prefer inspecting and using with E |
Terminal commands on the physical objects (ls ~/apuntes on the drawer) | Outside the PC, everything belongs to real life |
| A camera limited to ±60° | I want to turn all the way round and see the door |
| Recognising a hand-drawn T or F | Unreliable with a mouse and frustrating when it fails |
| An animation library (GSAP, Tween.js) | The curves we need fit in about 40 lines of our own |
| Real physics (Rapier, cannon-es) | Hundreds of kB, and nothing falls here: things are carried, slot in or go back |
Before you start: what is new in JavaScript in this version
v0.2 is written in more modern JavaScript than v0.1. If you are coming from the previous chapter, this is what changes:
| What you see | What it means |
|---|---|
const x = 5; / let y = 0; | Variables. const cannot be reassigned (almost everything); let can (counters, states). They replace v0.1’s var |
x => x * 2 | An arrow function: a short function. It is the same as function (x) { return x * 2; } |
class Muelle { constructor(…) { … } paso(dt) { … } } | A class: a mould for creating objects with their data and functions. new Muelle(0, 70, 11, 1.3) creates one (Muelle means spring) |
new Map() · objetos.set(clave, o) | A dictionary: it stores values by name |
x ?? y | If x does not exist (null or undefined), it is y |
new Promise(resolve => …) | A promise: an object that says “this will finish later” and lets you know (resolve) when it does |
async function f() { await something(); } | A function that can wait for a promise with await before moving on to the next line |
import * as THREE from 'three'; | A module: loads a library by name |
three.js as a module
In v0.1, three.js was loaded with a <script src>. v0.2 uses the modern way, with an importmap that says where each library comes from:
<script type="importmap">
{ "imports": { "three": "https://cdn.jsdelivr.net/npm/three@0.186.1/build/three.module.js" } }
</script>
<!-- … -->
<script type="module">
import * as THREE from 'three'; // "three" = the address in the importmap
const reduced = !!(window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches); // does the person want less motion?
const $ = s => document.querySelector(s); // shortcut: $('#velo') finds the element with id "velo"
| Line | What it does |
|---|---|
<script type="importmap"> | A table of names: when the code says 'three', the browser downloads it from that address, with the fixed version 0.186.1 |
<script type="module"> | The program is a module: it can use import |
import * as THREE from 'three' | Brings in the whole library and calls it THREE (that is why everything starts with THREE.) |
matchMedia('(prefers-reduced-motion: reduce)') | Asks the system whether the person has turned on “reduce motion”; reduced stores it as true or false |
const $ = s => … | A one-line arrow function to avoid writing document.querySelector every time |
A promise, step by step
It is the most important thing in this version, so it deserves a small example. Imagine three animations that have to run one after another. With promises:
await mueveBandeja(1); // 1. wait for the tray to slide all the way out… await anim(420, …); // 2. …then move the disc… await mueveBandeja(0); // 3. …and then slide the tray in
Each await “pauses” the program inside that function until the animation ends, but the rest of the page keeps working (the camera, the steam from the mug…). When the animation finishes, it calls resolve() and the function carries on with the next line. You will see it for real in “Putting a disc in, now as a list”.
How the code is organised
v0.1 was a single 790-line block of JavaScript. v0.2 is written as 12 modules (src/01-nucleo.js … src/12-bucle.js) that a script, construir.js, joins into a single HTML file. Why join them? Because JavaScript modules do not load when you open a file with a double click (file://): Chromium blocks them. This way the code is written tidily and it opens just as easily.
| Piece | What it does | Who it talks to |
|---|---|---|
| 01 core | Engine, curves, anim() with promises, Muelle (spring) and the event bus | Everyone |
| 02 data | Books, folders, mock exams, simulators, manual and bot | 04, 08, 09, 10 |
| 03 room | The fixed parts: walls, desk, tower, lamp, shelf, door | 07, 10, 12 |
| 04 objects | The registry: each object says its name and what it does | 06, 07, 08 |
| 05 camera | Turn = heading + look, the focus and the smoothing | 06 to 09 |
| 06 gestures | The state machine, inspecting, carrying and the zones | Calls what the objects declare |
| 07 actions | Disc drive, port, monitor, drawer, folder, mug, lamp, door | Fills in the uses |
| 08 book · 09 whiteboard · 10 screen | The open book, the whiteboard and the monitor with SergioLearns OS | Plugged in as modes |
| 11 accessibility | Tab, keys and announcements for screen readers | The modes |
| 12 loop | The frame and the start-up | Everyone |
The golden rule: the gestures do not know which objects exist. To add a new object you do not touch 06-gestos.js: you just register it.
How it is built, piece by piece
Animations that read like a list
In v0.1, chaining animations meant putting one tween inside another. In v0.2, anim() returns a promise: an object that is “fulfilled” when the animation ends. With await in front, the program waits for it to finish before moving on.
// The curves: they take the time progress x (from 0 to 1) and return how far it has moved
const curva = {
suave: x => (x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2), // eases in and out (the v0.1 one)
sale: x => 1 - Math.pow(1 - x, 3), // starts fast and slows down at the end
retroceso: x => { const c1 = 1.70158, c3 = c1 + 1; return 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2); }, // overshoots and comes back
rebote: x => { // falls and bounces, like the disc in the tray
const n = 7.5625, d = 2.75; // three ever-smaller parabolas
if (x < 1 / d) return n * x * x;
if (x < 2 / d) return n * (x -= 1.5 / d) * x + 0.75;
if (x < 2.5 / d) return n * (x -= 2.25 / d) * x + 0.9375;
return n * (x -= 2.625 / d) * x + 0.984375;
}
};
// anim(duration in ms, what to move, curve) → a promise fulfilled when it ends
function anim(dur, fn, ease = curva.suave) {
return new Promise(resolve => {
// with "reduce motion", the animation lasts 1 ms: it arrives in one frame
const a = { t0: performance.now(), dur: reduced ? Math.min(dur, 1) : dur, fn, ease, resolve, vivo: true };
anims.push(a); // the loop advances it every frame and calls resolve() at the end
});
}
The values, taken from running these same curves with node:
| Time | smooth | out | back | bounce |
|---|---|---|---|---|
| 0.1 | 0.004 | 0.271 | 0.409 | 0.076 |
| 0.3 | 0.108 | 0.657 | 0.907 | 0.681 |
| 0.5 | 0.500 | 0.875 | 1.088 | 0.766 |
| 0.7 | 0.892 | 0.973 | 1.080 | 0.931 |
| 0.9 | 0.996 | 0.999 | 1.014 | 0.988 |
Line by line, the key parts of anim():
| Code | What it does |
|---|---|
curva = { suave: x => …, … } | An object with four arrow functions; each one turns time progress into movement progress |
ease = curva.suave | If no curve is given, the smooth one |
return new Promise(resolve => { … }) | Returns a promise and keeps its resolve to call it at the end |
dur: reduced ? Math.min(dur, 1) : dur | With “reduce motion”, the animation lasts 1 ms |
anims.push(a) | Adds it to the list; the loop moves it forward every frame and, when it ends, calls a.resolve() |
Notice two details. The back curve goes past 1 (it reaches 1.099 at 0.6): that is why it “overshoots and comes back”. And the bounce drops from 0.910 to 0.766 between 0.4 and 0.5: that is the first bounce.
The drawer with weight: a spring
A real drawer does not move at a constant speed: it starts, picks up speed, goes slightly too far and comes back. That is a damped spring, and it is programmed with three numbers: stiffness (k), damping (c) and mass (m).
// Damped spring: F = −k·(x − target) − c·v
class Muelle {
constructor(x = 0, k = 120, c = 16, m = 1) { this.x = x; this.v = 0; this.obj = x; this.k = k; this.c = c; this.m = m; }
paso(dt) {
if (reduced) { this.x = this.obj; this.v = 0; return this.x; } // reduce motion: it arrives at once
const sub = Math.ceil(dt / 0.008), h = dt / sub; // split the frame into steps of at most 8 ms
for (let i = 0; i < sub; i++) {
const a = (-this.k * (this.x - this.obj) - this.c * this.v) / this.m; // acceleration = force / mass
this.v += a * h; this.x += this.v * h; // velocity first, then position
}
return this.x;
}
}
const cajonM = new Muelle(0, 70, 11, 1.3); // heavy: low stiffness and a little bounce
| Code | What it does |
|---|---|
constructor(x = 0, k = 120, c = 16, m = 1) | Creates the spring: starting position and its three numbers (with default values) |
this.v = 0; this.obj = x; | It starts still, with the target where it is |
Math.ceil(dt / 0.008) | How many 8 ms pieces this frame is split into (a 16 ms frame is 2 pieces) |
const a = (… ) / this.m; | The acceleration: force divided by mass |
this.v += a * h; this.x += this.v * h; | First the velocity changes and then the position, using the new velocity |
return this.x; | The new position: the loop uses it to move the drawer (drawer.position.z = cajonM.paso(dt)) |
The important line is the force. −k·(x − obj) pulls towards the target, harder the further away you are (a stretched spring). −c·v brakes, harder the faster you go (like air or friction). The acceleration is that force divided by the mass, and it is used to update the velocity and then the position.
| Time | Position | Velocity |
|---|---|---|
| 0.1 s | 6.3 cm | 100.9 cm/s |
| 0.3 s | 26.4 cm | 72.7 cm/s |
| 0.5 s | 33.1 cm (3.1 too far) | 3.9 cm/s |
| 0.7 s | 31.6 cm | −11.7 cm/s |
| 1.0 s | 29.7 cm | −0.9 cm/s |
| 1.5 s | 30.0 cm | 0.2 cm/s |
Why does it overshoot? Because of the damping ratio, ζ = c / (2·√(k·m)) = 11 / (2·√(70 · 1.3)) = 11 / (2 · 9.54) = 0.577. If ζ were 1 or more, it would arrive without overshooting (like a door with a closer); at 0.577, it goes slightly past and comes back. That small overshoot is what the eye reads as “weight”.
For the curious. “Velocity first, then position” has a name: semi-implicit Euler. If you do it the other way round (explicit Euler), the spring gains a little energy on every step and, with long frames, ends up oscillating more and more. That is also why the frame is split into 8 ms steps: the smaller the step, the more stable it is.
And the handle: when you drag it, the drawer does not move, the spring’s target does. The drawer follows it with its delay, and that is why it feels heavy:
alArrastrar: {
empieza(p) { this.y0 = p.y; this.z0 = cajonM.obj > 0.15 ? CAJON_ABIERTO : 0; }, // where the pull starts from
mueve(e) { cajonM.obj = clamp(this.z0 + (e.clientY - this.y0) * 0.0016, 0, 0.33); }, // 1 px = 1.6 mm of target, at most 33 cm
suelta() { if (cajonM.obj > 0.14) abreCajon(); else cierraCajon(); } // on release: fully open or fully closed
}


The camera that turns all the way round
In v0.1 the turn was −mx · 1.05: 60° each way at most. To turn all the way round you need to separate two ideas: where your body is facing (the heading) and how far you turn your head (the look). The final turn is the sum.
// the heading only turns if the mouse ENTERED the edge while free (otherwise, dropping something near the edge made the room spin by itself) if (Math.abs(rig.mx) <= BORDE) rig.bordeListo = gesto.estado === 'libre'; const puedeGirar = rig.bordeListo && gesto.estado === 'libre' && !gesto.pulsado && !teclado.activo; // inside the edge strip (|mx| > 0.86), the heading turns faster the closer the mouse is to the edge if (puedeGirar && Math.abs(rig.mx) > BORDE) rig.rumbo -= Math.sign(rig.mx) * VEL_BORDE * ((Math.abs(rig.mx) - BORDE) / (1 - BORDE)) * dt; rig.rumbo -= rig.teclaGiro * VEL_TECLA * dt; // A and D (or the arrow keys) turn it too ty = rig.rumbo - rig.mx * 1.05 * rig.sensib; // turn = heading + look (the v0.1 one)
| Code | What it does |
|---|---|
rig.bordeListo = gesto.estado === 'libre' | While the mouse is outside the edge, it notes whether you are free; that is how it knows you entered the edge while free |
puedeGirar = … && !gesto.pulsado && !teclado.activo | It only turns if you are not doing something else with the mouse or using the keyboard |
rig.rumbo -= Math.sign(rig.mx) * VEL_BORDE * (…) * dt | Turns the heading towards the mouse side, faster the closer to the edge, multiplied by dt so it behaves the same at any frame rate |
rig.rumbo -= rig.teclaGiro * VEL_TECLA * dt | teclaGiro is −1, 0 or 1 depending on whether you press A, nothing or D |
ty = rig.rumbo - rig.mx * 1.05 * rig.sensib | The final turn: heading + look; sensib drops to 0.45 while you are carrying something |
With BORDE = 0.86 and VEL_BORDE = 1.6 rad/s, the “strength” goes from 0 to 1 across the edge strip:
| Mouse (mx) | Strength | Turning speed |
|---|---|---|
| 0.86 | 0.00 | 0 °/s |
| 0.90 | 0.29 | 26.2 °/s |
| 0.95 | 0.64 | 58.9 °/s |
| 1.00 | 1.00 | 91.7 °/s |
The 0.95 row worked out: strength = (0.95 − 0.86) / 0.14 = 0.64; speed = 1.6 · 0.64 = 1.03 rad/s, which is 1.03 · 57.3 ≈ 58.9 °/s. With the mouse right at the edge, a full turn (360°) takes about 4 seconds.
For the curious. When you press Esc, the camera goes back to looking at the desk. But if you have turned round twice, the heading is 4π, and animating it down to 0 would spin you twice the other way. rumboACero() first subtracts the whole turns (Math.round(heading / 2π) · 2π) so it goes back the short way.

A registry, a state machine and a bus
The heart of this version is three small pieces. The first, the registry: each object signs up with its name, its meshes and what it does.
/* registrar(key, {nombre, mallas, raiz, movil, alClic, alUsar, alArrastrar, insp, activo}) */
function registrar(clave, o) {
o.clave = clave;
o.activo = o.activo || (() => gesto.estado === 'libre'); // by default, it can only be touched while free
objetos.set(clave, o);
o.mallas.forEach(m => {
m.userData.clave = clave; pickables.push(m); // the ray will know which object each mesh belongs to
// each object clones its materials: that way its coral glow does not spread to others sharing the material
m.material = Array.isArray(m.material) ? m.material.map(x => x.clone()) : m.material.clone();
});
if (o.raiz) guardaCasa(o); // records its "home": where it goes back to with Esc
return o;
}
| Code | What it does |
|---|---|
o.activo = o.activo || (() => gesto.estado === 'libre') | If the object does not say when it can be touched, it can only be touched while free |
objetos.set(clave, o) | Stores it in the registry by name ('cajon', 'disco-fp1'…) |
m.userData.clave = clave; pickables.push(m) | Each mesh records which object it belongs to, and joins the list of things the ray can touch |
m.material.clone() | Each object has its own materials, so its glow does not spread |
guardaCasa(o) | Records its parent, position and rotation: its “home”, where it goes back to |
The second, the state machine. The state is a string (libre, inspeccion, llevar, lectura, pizarra, ocupado…) and each special mode is plugged in with modo():
const gesto = { estado: 'cargando', pulsado: null, hover: null, obj: null, arrastre: null };
const modos = {};
function modo(nombre, h) { modos[nombre] = h; } // a mode = what to do on press, move, release, keys and Esc
function cambia(estado) { gesto.estado = estado; rig.bordeListo = false; bus.emit('estado', estado); actualizaPunto(); }
When you press the mouse button, the gesture system looks up the mode for the current state and hands it the event. The open book, the whiteboard and the mug know nothing about each other: each one is a mode. And ocupado (busy) is a special state that does nothing: it blocks input while an animation lasts, so you cannot pick up a book while the disc is going in.
The third, the event bus: modules notify each other without knowing each other.
const bus = {
oy: {}, // who listens to each event
on(ev, fn) { (this.oy[ev] = this.oy[ev] || []).push(fn); }, // "let me know when ev happens"
emit(ev, dato) { (this.oy[ev] || []).forEach(fn => fn(dato)); } // "ev has happened": notify everyone
};
The disc case listens to hover to open when you get close, without the gesture system knowing the case exists. It is the same pattern as browser events (addEventListener), done in five lines.
Inspecting: turning the object in your hand
When you grab an object, it comes in front of the camera and the room darkens around it. Dragging turns it. It sounds simple, but there is a catch: turn it about which axes?
function poseInspeccion(o, salidaPos, salidaQuat) {
camera.getWorldDirection(_v); // where the camera is looking
salidaPos.copy(camera.position).addScaledVector(_v, insp.dist); // the object, "dist" metres in front (the wheel changes it)
_q2.setFromEuler(o.insp.rot); // its base pose: how it is shown at first
salidaQuat.copy(camera.quaternion).multiply(insp.q).multiply(_q2); // camera · your turn · base pose
}
function giraInspeccion(dx, dy) {
// turning in camera space: dragging right turns about the SCREEN's vertical axis
_q.setFromAxisAngle(new THREE.Vector3(0, 1, 0), dx); insp.q.premultiply(_q); // premultiply = on the left
_q.setFromAxisAngle(new THREE.Vector3(1, 0, 0), dy); insp.q.premultiply(_q);
}
| Code | What it does |
|---|---|
camera.getWorldDirection(_v) | Stores in _v where the camera is looking (an arrow of length 1) |
salidaPos.copy(camera.position).addScaledVector(_v, insp.dist) | The position in your hand: from the eyes, dist metres in that direction |
_q2.setFromEuler(o.insp.rot) | The object’s base pose (for example, the book with its cover facing you) |
camera.quaternion · insp.q · _q2 | The final rotation: the camera’s, then yours, then the base pose |
setFromAxisAngle(new THREE.Vector3(0, 1, 0), dx) | A rotation of dx radians about the vertical axis |
insp.q.premultiply(_q) | Adds it to your turn, on the left |
3D rotations are stored as quaternions (four numbers that represent a rotation) and they are combined by multiplying them. The order matters: multiplying on the left (premultiply) applies the new turn after the previous ones, on the fixed axes of the screen. Multiplying on the right would apply it on the object’s axes, which are already turned: after half a turn, “drag right” would turn it left.
For the curious. Why quaternions and not three angles? With angles (Euler), after turning 90° about one axis, the other two can line up and you lose a degree of freedom: the famous gimbal lock. Quaternions do not have that problem and they also interpolate nicely with slerp, which is what the animation uses so the object flies smoothly into your hand.

Putting a disc in, now as a list
Compare with v0.1: six levels of tween inside tween. With promises, the same sequence reads top to bottom:
async function meteDisco(o) {
cambia('ocupado'); gesto.obj = o; // block input while it lasts
if (torre.disco && torre.disco !== o) await sacaDisco(false); // if there was another one, it comes out first
if (torre.bandeja < 1) await mueveBandeja(1); // 1. the tray slides out
scene.attach(o.raiz);
tray.updateMatrixWorld(true);
// two points in tray coordinates, converted to the world: 5 cm above it and inside the slot
const encima = new THREE.Vector3(0, 0.05, 0).applyMatrix4(tray.matrixWorld), dentro = new THREE.Vector3(0, 0.006, 0).applyMatrix4(tray.matrixWorld);
const p0 = o.raiz.position.clone(), q0 = o.raiz.quaternion.clone(), q1 = new THREE.Quaternion();
await anim(420, e => { o.raiz.position.lerpVectors(p0, encima, e); o.raiz.quaternion.slerpQuaternions(q0, q1, e); }, curva.suave); // 2. it flies above, straightening up
await anim(420, e => o.raiz.position.lerpVectors(encima, dentro, e), curva.rebote); // 3. it falls and bounces
tray.attach(o.raiz); // 4. from here on it moves with the tray
await mueveBandeja(0, 460); // 5. it goes in
torre.disco = o; gesto.obj = null; $('#velo').classList.remove('on');
pantalla.pon('simulacro', o.datos); parpadeoLed(1400); // 6. the monitor loads the mock exam and the LED blinks
}
| Code | What it does |
|---|---|
async function meteDisco(o) | async: it can use await inside (meteDisco means “put the disc in”) |
cambia('ocupado') | The state machine switches to “busy”: no other gestures while it lasts |
if (torre.disco && torre.disco !== o) await sacaDisco(false) | If there was another disc inside, it takes it out first, and waits |
.applyMatrix4(tray.matrixWorld) | Converts a point from tray coordinates (5 cm above, 6 mm inside) to world coordinates |
lerpVectors(p0, encima, e) | Blends two positions: with e = 0 it is at p0; with e = 1, at encima (above) |
slerpQuaternions(q0, q1, e) | The same with the rotation: the disc straightens up as it flies |
curva.rebote | The fall uses the bouncing curve |
pantalla.pon('simulacro', o.datos) | The monitor shows that disc’s mock exam |
Each await waits for the line before it to finish. The code says exactly what you see, in the same order. The attach in step 4 is the same trick as in v0.1.


Target zones: “close” is measured on screen
While you carry a disc, the program has to know whether you are close to the disc drive to make it glow. The first attempt measured that distance on the desk plane: where the mouse ray hits the desk compared with where the drive is. And the disc never fitted.
The reason is geometric. The slot is 1.10 m high and your eyes are at 1.22 m: the ray from your eyes to the slot drops only 12 cm over 1.17 m. To drop down to the desk (0.765 m) it has to travel 3.8 times that distance: it hits the desk at 4.4 m, far behind the tower and outside the room. When you aim at the slot, “your point on the desk” is miles away from the slot.
The fix is to measure where you measure: on screen. The zone is projected onto the screen and compared with the mouse:
// close = close ON SCREEN: compare where the mouse points with where the zone appears _v.copy(z.punto).project(camera); // the zone's 3D point → screen coordinates (−1 to 1) const d = Math.hypot((ndc.x - _v.x) * camera.aspect, ndc.y - _v.y); // distance to the mouse; · aspect so it is a circle, not an ellipse z.prox = _v.z < 1 ? clamp(1 - d / z.radio, 0, 1) : 0; // 1 = right on it, 0 = outside the radius (or behind the camera)
| Code | What it does |
|---|---|
_v.copy(z.punto).project(camera) | Projects the zone’s 3D point (the slot) onto the screen: x and y from −1 to 1, like the mouse |
(ndc.x - _v.x) * camera.aspect | The horizontal distance, corrected for how wide the screen is (otherwise the circle would be squashed) |
Math.hypot(a, b) | The straight-line distance: √(a² + b²) |
_v.z < 1 ? … : 0 | If the zone is behind the camera, it does not count |
clamp(1 - d / z.radio, 0, 1) | 1 if the mouse is right on it, 0 at a distance of radio or more, and in between otherwise |
With that closeness, prox, three things happen at once: the zone glows more (1.4 + 2.4·prox, with a small pulse), the object rises towards the zone’s height and turns the way it is going to fit. So you can see it “is going to go in” before you let go.
“Close” in 3D depends on where you are looking from. If what matters is where the person is pointing, measure on screen (with project()), not in the world. It took a failed test to realise it, and it is the most useful mistake of this version.
There was a second part to the same bug: while you carried the disc, it hid behind the tower (and inside it). Now the plane it is dragged on has limits: always in front of the tower and the monitor.
The page that curls
In v0.1, turning a page meant rotating a flat sheet, which also vanished under the cover. In v0.2 the page bends as it turns, and does not stretch. The trick is to build it as a chain of 24 equal pieces, each one at a slightly different angle:
// a(s) = θ − β·sin(πp)·(s/W)^1.5 (s = distance from the spine, W = page width, p = turning progress) const s = (i + 0.5) * ds, a = th - beta * Math.sin(Math.PI * p) * Math.pow(s / W, 1.5); x += Math.cos(a) * ds; z += Math.sin(a) * ds; // move one piece of length ds in direction a
Read it like this: θ = π·p is the angle at the root, next to the spine, which goes from 0° to 180°. The second term delays the tip: sin(πp) is 0 at the start and at the end (flat page) and 1 halfway through (maximum curl), and (s/W)^1.5 makes the delay grow towards the tip. Since every piece has the same length (ds), the whole page is always the same length: it does not stretch.
| Progress p | Root | Tip | Tip x | Tip z | Length |
|---|---|---|---|---|---|
| 0 | 0° | 0° | 15.80 cm | 0.00 cm | 15.800 cm |
| 0.25 | 45° | 8.5° | 13.38 cm | 7.86 cm | 15.800 cm |
| 0.5 | 90° | 38.4° | 5.35 cm | 14.26 cm | 15.800 cm |
| 0.75 | 135° | 98.5° | −7.86 cm | 13.38 cm | 15.800 cm |
| 1 | 180° | 180° | −15.80 cm | 0.00 cm | 15.800 cm |
These numbers were checked with node before being used. The last column is the proof: 15.800 cm throughout the turn. Halfway (p = 0.5) the root is already upright (90°), but the tip is at 38.4°: 0.9 · 1 · 1 = 0.9 rad less, which is 51.6° behind.


For the curious. If you grab the page by a corner, β changes with the height of each row (1 + 0.55·grip·y) and the page bends diagonally. And the back of the page uses the same texture mirrored (repeat.x = −1), so there is no need to draw each page twice.
The whiteboard, the mug and the keyboard
The whiteboard has three layers that are combined into one texture: the background (calendar, countdown and question of the day), what you write freehand and the answer. That way the eraser rubs out your writing without rubbing out the calendar. When you tap T or F, the marker goes to the box and writes the letter stroke by stroke: each letter is a list of points (a polyline) that is followed along its length.

The mug is grabbed like any other object; with E you bring it closer, the steam thickens and forms the conversation with Sergio Bot. For now it replies with sample answers: the real bot lives on the website, with its key and its quota, and the prototype is not there yet.


Accessibility with no visible buttons
Removing the buttons cannot leave out people who use the keyboard or a screen reader. The solution is an invisible list: one button per object (36), with its name, which only appears when it gets the focus. Tab goes through the objects, the camera looks at each one, it glows and its name is announced; Enter grabs it and E uses it. The first Tab shows “Go to the normal website, without 3D”.


A recording caught a serious bug: when leaving the mug, the keyboard focus jumped back to the top of the page, and the next Tab + Enter took you out of the room. The function that fixes it:
// when leaving a mode that types (mug, keyboard), the focus goes back to its object in the list (if the keyboard was in use)
// or to the canvas, so the next Tab carries on through the objects and does not jump to the link at the top
function devuelveFoco(clave) {
const b = teclado.activo && nav.querySelector('[data-clave="' + clave + '"]');
if (b) b.focus({ preventScroll: true }); else canvas.focus({ preventScroll: true });
}
The decisions
| Decision | Alternatives | Why this one |
|---|---|---|
| No buttons; a dot instead of the cursor; a manual inside the world (mine) | Buttons as in v0.1 | The clean experience I imagined |
| Inspect mode like in Resident Evil (mine) | Making the click perform the action | Discovering details in the objects |
| Outside the PC everything is physical (mine) | A terminal look everywhere | The terminal belongs to the virtual world |
| Full turn and a door behind (mine) | A ±60° turn | It is the way out and the start of the v0.5 arrival |
Three.js 0.186.1 as a module, with importmap | r128 (v0.1); 0.187.0 | A current version; 0.187.0 was five days old and we use one at least two weeks old |
| 12 modules joined into one HTML | Several .js files served separately | Modules do not load from file:// |
| State machine + registry + bus | Lots of scattered ifs | One place for each gesture; objects that do not know each other |
anim() with promises | Nested tweens | Sequences read top to bottom |
| Home-made curves | GSAP, Tween.js | About 15 lines, no dependencies or licences |
| Spring (semi-implicit Euler, 8 ms steps) | A fixed curve; a physics engine | Weight without hundreds of kB |
| Zones measured on screen | On the desk plane | On the desk it never fitted |
| The page as a chain of 24 pieces | A flat sheet; a shader | It does not stretch and it is easy to explain |
| An invisible list for Tab | A visible menu | Keyboard and screen reader with no interface on show |
Testing and performance
All measured with scripts (Playwright and node):
| What | v0.1 | v0.2 |
|---|---|---|
escritorio-3d.html | 925 lines · 68.8 kB | 2,149 lines · 142.9 kB |
| Compressed (brotli) | 18.5 kB | 37.9 kB |
| three.js compressed (brotli) | 118.0 kB (r128) | 306 kB (0.186.1: module + core) |
| Draw calls | 107 | 197 |
| Triangles | 3,448 | 4,194 |
| Time to ready (headless, 1280 × 720) | — | 1.8 s |
| Console errors | 0 | 0 |
Smoothness: on my laptop, v0.2 runs at about 60 frames per second, sometimes dropping to 57. The headless browser used in the tests, which draws with the processor, gives between 4 and 11: that is why real measurements have to be taken on a real computer.
197 draw calls is a lot for only 4,194 triangles: every box is a mesh and every mesh is a call. That gets fixed in v0.4, when the meshes are merged into Blender models.
Accessibility:
| Check | Result |
|---|---|
| First Tab | “Go to the normal website, without 3D” |
| Objects in the Tab order | 36, each with its name |
| Screen readers | An aria-live region with the name and what to do |
| “Reduce motion” | Two screenshots at rest 1.5 s apart: 0 pixels different |
| Contrast | Every text passes AA (4.5:1); the tightest, the whiteboard’s red marker, 4.51:1 |
What went wrong (and how I fixed it)
- The disc never fitted. Closeness was measured on the desk and the disc drive is 34 cm higher. Now it is measured on screen (you saw it above) and the disc never goes behind the tower.
- The room spun by itself when you dropped a disc into the tower: the mouse was left on the right edge, which is the turning zone. Now the edge only turns if the mouse enters it while free.
- A comment ate half a line. When a
//comment was added at the end of the line that placed each folder, what came after it on that same line (drawer.add(g)) got commented out: the folders were not in the drawer and putting one back crashed the program (Cannot read properties of null). The clip recording caught it. - Tab took you out of the room when leaving the mug (fixed with
devuelveFoco). A recording caught that one too. - The whiteboard wrote mirrored. It is rotated 90° and the canvas coordinate grows towards −z; the first calculation had the sign the wrong way round.
- The pages were hard to read: with the hand light, the paper came out almost white and the text grey. The light was lowered and the text made darker and bolder.
- The mug’s text came out backwards (a mirrored texture that was not needed) and what you typed got scrambled with accents and “¿”. Now normal letters are picked up from the key press and composed ones from the
inputevent. - The folder labels could not be seen: they were in the middle of the cover, hidden by the folder on top. Now they are on the front edge.
A // at the end of a line comments out everything after it on that line, even if it is code. If you write several statements on one line, put the comment on the line above. This bug gave no error on load: only when putting a folder back.
And one thing that is not a code bug, but a content one: the objects’ trivia fell short. It is too shallow, and I want it to tell real details about the website. I am noting it down for the next version.
How I worked with the AI in this version
- What I asked for: the list I wrote after testing v0.1 (no buttons, a manual inside the world, discs you drag, pages that do not vanish, folders you can pick up, a use for the mug…) and, in the round of questions, my decisions: the mug with Sergio Bot, the whiteboard, the disc case and the pen pot, inspecting like in Resident Evil, everything physical outside the PC and the door behind you.
- What Claude did: before coding, it drew the sketches and wrote the requirements; then, the 12 modules; and it tested everything with scripts that move the mouse, write to the console which state the program is in and record the clips. Three of this version’s bugs were caught by those recordings. At the end, it measured the performance and documented everything for this chapter.
- What I did: test it. First, opening the drawer and grabbing a folder. Measuring the frame rate on my laptop (about 60). And noting what did not convince me: the objects’ trivia is too shallow, and I wrote a new list of improvements that became version 0.2.1.
- What I learnt from the process: the more concrete the decision, the better the result. “Let me inspect it like in Resident Evil” says much more than “let me pick things up”.
What I have learnt
- A state machine brings order to an interface with no buttons: each gesture means something different depending on the state, and Esc gets you out by itself.
- Promises turn a multi-step animation into a list that reads top to bottom.
- A spring gives weight without a physics engine: stiffness, damping and mass.
- “Close” is measured on screen, not in the world, when what matters is where the person is pointing.
- Recording is testing: three bugs in this version were caught by the recording scripts, not by eye.
- With AI, deciding well is half the work: concrete decisions turn into code much better than vague ideas.
The full code
On GitHub, in sergiolearns-codigo/proyectos/escritorio/v0.2: escritorio-3d.html (the prototype ready to open with a double click, with internet for three.js and the fonts), the src/ folder with the 12 modules (edit there) and construir.js, which joins them (node construir.js).
What comes next
Version 0.3 brings SergioLearns OS: a computer inside the screen with its own system, its own cursor and its apps, video games that teach something from the degree and achievements as discoveries (the objects’ clues, like the back of a disc or the bottom of the mug, will finally unlock something). Before that comes v0.2.1, with fixes (the disc you carry looks small, for example) and a new room: a window behind the monitor showing the time in the Canary Islands, the shelf on the right-hand wall and more furniture. Both are told together in chapter 4.
It is all in chapter 4: from a fixed camera to a room you walk around (and play), which goes up to v0.2.5. Meanwhile, the Sergio’s Room report has the status of the whole project.
Keep goingAll Sergio's Room articlesDid this article help you? Here is how you can support SergioLearns →


