UNPKG

@polygonjs/polygonjs

Version:

node-based WebGL 3D engine https://polygonjs.com

58 lines (57 loc) 2.18 kB
"use strict"; import { MathUtils, Vector3, Quaternion, Euler } from "three"; var DeviceOrientationControls = function(object) { var scope = this; this.object = object; this.object.rotation.reorder("YXZ"); this.enabled = true; this.deviceOrientation = {}; this.screenOrientation = 0; this.alphaOffset = 0; var onDeviceOrientationChangeEvent = function(event) { scope.deviceOrientation = event; }; var onScreenOrientationChangeEvent = function() { scope.screenOrientation = window.orientation || 0; }; var setObjectQuaternion = function() { var zee = new Vector3(0, 0, 1); var euler = new Euler(); var q0 = new Quaternion(); var q1 = new Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5)); return function(quaternion, alpha, beta, gamma, orient) { euler.set(beta, alpha, -gamma, "YXZ"); quaternion.setFromEuler(euler); quaternion.multiply(q1); quaternion.multiply(q0.setFromAxisAngle(zee, -orient)); }; }(); this.connect = function() { onScreenOrientationChangeEvent(); window.addEventListener("orientationchange", onScreenOrientationChangeEvent, false); window.addEventListener("deviceorientation", onDeviceOrientationChangeEvent, false); scope.enabled = true; }; this.disconnect = function() { window.removeEventListener("orientationchange", onScreenOrientationChangeEvent, false); window.removeEventListener("deviceorientation", onDeviceOrientationChangeEvent, false); scope.enabled = false; }; this.update = function() { if (scope.enabled === false) return; var device = scope.deviceOrientation; if (device) { var alpha = device.alpha ? MathUtils.degToRad(device.alpha) + scope.alphaOffset : 0; var beta = device.beta ? MathUtils.degToRad(device.beta) : 0; var gamma = device.gamma ? MathUtils.degToRad(device.gamma) : 0; var orient = scope.screenOrientation ? MathUtils.degToRad(scope.screenOrientation) : 0; setObjectQuaternion(scope.object.quaternion, alpha, beta, gamma, orient); } }; this.dispose = function() { scope.disconnect(); }; this.connect(); }; export { DeviceOrientationControls };