Three.js Device Orientation (Gyroscope) Controls Tutorial

The one place I see the Three.js mobile library shining best is on our mobile devices. When I was first getting started, I spent days trying to find the perfect library to tap into the gyroscope controls in three.js. I ended my search unsuccessfully and worked towards building the perfect set that worked for my application.

After compiling a few resources together and hours of trial and error, I’ve come up with what I believe is the best solution and I’m very happy to be able to share it with the public.

Hint: If you’re not interested in the tutorial and just want the file, I’ve linked to it at the bottom of this post.

Get Started

If you haven’t already, fork the three.js library from Github to make it your own, or just download the file and work directly in there.

The first step is to add two pretty complex functions into the object. I’ll even admit I’m not 100% certain what they do at a granular level, but they work well! Add these anywhere within the main OrbitControls object.

These two functions are the backbone if converting the values returned from the deviceorientation event (alpha, beta & gamma) to a quaternion which is how the OrbitControls will play nice with the gyroscope.

The next step is to add our two event listeners. We’ll listen for the deviceorientation event which provides us the exact values for how our phone is positioned, and the event when we switch between portrait and landscape. Drop these in that object as well.

Now we need to modify the update functions. Look for the this.update declaration and first add these two variables before the returned enclosure.

Now at the bottom of the enclosure before returning false, add this block:

The location of this code is important, so here is the entire update function incase I wasn’t very clear.

Phenominal, that’s it! The orbitcontrols will now work flawlessly with your gyroscope. You can even use them at the same time, cool right? See my updated example here with them implemented.

Here is the link to my completed OrbitControls.js file.

Leave a Reply