WebGL: Incorporating Device Orientation

At last night’s DCJS Meetup (specifically Sean’s talk referencing this) I learned that a means of reading the 3D orientation of a device has been readily available for some time. Descriptions were not hard to find.

Setting up the listener is easy enough. The window.DeviceOrientationEvent test will actually pass on a lot of devices, including my laptop, even if they don’t actually fire off the update events, therefore I initialize the angles to null and use them as a test for updating the camera orientation.

If the orientation events don’t fire then I let the camera move and continue to look at the origin of the scene as before but if the events to fire I stop the camera from moving and update its orientation in space instead. The 90 degree adjustment for rotation around the X-axis was something I added to make the view make sense. That may be an artifact of the coordinate system I set up. An additional adjustment may be necessary on Firefox on some devices.

Here’s a direct link to test on your mobile device. Let me know if it works for you. Here‘s a different way to see if your device even supports this functionality.

This setup looks like it works on my iPhone for small rotations but it really doesn’t behave the way I’d want it to. There’s clearly a lot more going on. I’m going to dig into that a bit later but in the meantime I found an even more direct — and easier — way to accomplish this. Addendum, February 22, 2017: No, that’s not what was going on, this is what was going on. The rotations I did accounted for the directional vector but not the rotation around that vector. This is the extra factor addressed in DeviceOrientationControls.js.

Three.js already includes a way to incorporate a device’s orientation, and that is by including the capabilities in DeviceOrientationControls.js. An example is here. I pulled all of the previous code out and replaced it with all of three new lines identified below, and also set the orbit increment to zero.

It could not be easier.

My quick hack for checking this out on your device directly is here. It won’t do anything on a device that doesn’t support sensing of orientation but it looks and works great on my phone.

The next thing I’d have to do is figure out how to determine whether the device supports this new addition and revert to the previous orbit-and-look-at-the-origin behavior.

This entry was posted in Software and tagged , , , . Bookmark the permalink.

Leave a Reply