WebTech1223411 logo WebTech1223411Web tech, read closely
Games

How the Pointer Lock API Makes Mouse Aim Work in Browser Games

The bug report said "aim jumps randomly", which is the kind of report that makes a QA tester sigh.

A browser shooter with a hidden cursor and a crosshair in the centre

The bug report said "aim jumps randomly", which is the kind of report that makes a QA tester sigh. The game was a small browser shooter, and on about one in five test machines the camera would occasionally snap sideways by thirty or forty degrees, as if the player had flicked the mouse across the desk. Nobody had. It took two days to trace it to a single oversized mouse event coming out of the Pointer Lock API, on one particular combination of operating system and browser.

Pointer Lock is the piece of the web platform that makes mouse aiming in browser games possible at all. Without it, the cursor hits the edge of the screen and your character stops turning. With it, you get raw movement deltas and an invisible cursor that never runs out of room. It is a small API, and most tutorials cover it in ten lines. The trouble lives in the details those tutorials skip, and that is where a cross browser tester ends up spending her week.

What the API actually gives you

You call requestPointerLock() on an element, usually the game canvas. The browser hides the cursor, stops it moving, and starts reporting how far the mouse would have moved through two properties on each mousemove event: movementX and movementY. Your game reads those numbers every frame and turns them into camera rotation.

A few rules come with it. The request has to come from a user gesture, typically a click on the canvas, so a page cannot grab your mouse on load. The browser shows a short notice telling the player to press Esc to get the cursor back, and Esc always releases the lock; a game cannot override that. Two events tell you what happened: pointerlockchange when the lock starts or ends, and pointerlockerror when a request fails. You check document.pointerLockElement to see which element, if any, currently holds the lock.

If your game runs inside an iframe, which is common on game portals, the iframe's sandbox attribute needs allow-pointer-lock, or every request fails with an error that does not always say why. I have lost an afternoon to that one.

Where it goes wrong in real browsers

Mouse acceleration you did not ask for

By default the movement values pass through the operating system's pointer settings, including acceleration. That is fine for a desktop cursor and terrible for aiming, because the same physical hand movement turns the camera by different amounts depending on how fast you moved. Players who come from desktop shooters feel it immediately and describe the game as "floaty".

Chromium based browsers accept an options object, requestPointerLock({ unadjustedMovement: true }), which asks for raw movement without acceleration. At the time I last tested, Firefox and Safari did not support that option, so you need to handle the request failing and fall back to the default. In Chromium the call also returns a promise, which makes that fallback cleaner to write than the older event only pattern.

Spikes in movementX

This was the cause of my "aim jumps randomly" bug. On some machines, under some conditions, a single mousemove event reports a huge movementX value, hundreds of pixels in one event, usually right after the lock engages or when the window regains focus. Browser bug trackers have carried reports of this for years. The defensive fix most game developers use is to ignore or clamp any single delta above a sanity threshold. In our case, discarding events larger than 300 pixels and logging them removed every reported snap, and the log showed they arrived almost exclusively in the first 100 milliseconds after lock.

Re-locking too soon after Esc

If a player presses Esc and then clicks straight back into the game, Chrome may refuse the new request if it comes too quickly after the user exited, roughly within a second in my tests. The error is a pointerlockerror with no friendly explanation. A pause menu that appears on unlock, with a "click to resume" button, avoids the problem neatly, because by the time the player reads it and clicks, enough time has passed.

Turning deltas into a sensitivity players recognise

Most browser shooters invent their own sensitivity scale, so a player who has spent years tuning their aim elsewhere has to start again. There is an easy improvement. Many desktop shooters built on Valve's Source engine rotate the camera by 0.022 degrees per mouse count, multiplied by the sensitivity setting. If your game uses the same base value and receives unadjusted movement, a player can type in the number they already know and get roughly the same turn per centimetre.

"Roughly" is doing honest work in that sentence. Movement values can be affected by display scaling, and I have seen different results between 100 percent and 150 percent Windows scaling on the same machine. I would not promise players an exact match, but getting them within a few percent is still far better than an unexplained slider from 1 to 100.

Advice I would not take

A common suggestion on forums is to skip Pointer Lock and recentre the mouse yourself with some trick. Browsers do not let a page move the system cursor, for good security reasons, so every version of that idea ends with the cursor escaping the window during a fast turn. Pointer Lock is the only supported route, and the fixes above are cheaper than any workaround.

Treat every movementX value as untrusted input. The mouse is hardware, the browser is software, and the operating system sits between them.

A test pass worth running

When I review a browser game that uses mouse aim, this is the pass I run, in this order:

  1. Lock and unlock twenty times in a row, using click and Esc, watching the console for pointerlockerror.
  2. Alt tab away and back while locked, then check whether the first frame after return produces a camera jump.
  3. Repeat both in Chrome, Firefox and Safari, and in Chrome with unadjustedMovement on and off.
  4. Change the operating system's display scaling and repeat a slow 360 degree turn, measuring the mouse distance on the desk.
  5. Load the game inside a sandboxed iframe, as a portal would, and confirm the lock still works.

The full pass takes about forty minutes on three browsers. It catches most of the input complaints I would otherwise read in reviews. If your game also supports controllers, the matching notes on how the Gamepad API connects controllers are worth reading alongside this, and since mouse deltas are applied each frame, how requestAnimationFrame keeps motion smooth explains where to apply them.

Your next step

Open your game, lock the pointer, and add one line that logs any movementX above 300 for a single session of normal play. If the log stays empty on your machine, send the build to two friends on different systems and ask them to play for ten minutes. You will know within a day whether your players are getting the spikes. More notes on how browsers handle input live in our browsers section.

MC
Maren Castellanos

Maren worked in cross-browser QA before editing, and knows the DevTools Network tab better than most people know their inbox. She writes about how browsers load and render pages and about the tools that show what is really happening.

More posts by Maren

More in Games

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu haskell iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto