Skip to content

Instantly share code, notes, and snippets.

@demonixis
Created October 3, 2014 14:51
Show Gist options
  • Select an option

  • Save demonixis/ab1ab0f6ef4212aae19a to your computer and use it in GitHub Desktop.

Select an option

Save demonixis/ab1ab0f6ef4212aae19a to your computer and use it in GitHub Desktop.
A mobile VR compatible class to use with Babylon.js
var MobileVRCamera = (function() {
var mobileVR = function(position, scene) {
BABYLON.OculusCamera.call(this, "MobileVR Component", position, scene);
this.vrEnabled = false;
this.screenOrientation = 0;
this.deviceOrientation = {
alpha: 0,
beta: 0,
gamma: 0
};
this._onOrientationEvent = this._onOrientationEvent.bind(this);
};
mobileVR.prototype = Object.create(BABYLON.OculusCamera.prototype);
mobileVR.prototype.attachControl = function(element, noPreventDefault) {
BABYLON.OculusCamera.prototype.attachControl.call(this, element, noPreventDefault);
this._startVR();
};
mobileVR.prototype.detachControl = function(element) {
BABYLON.OculusCamera.prototype.detachControl.call(this, element);
this.vrEnabled = false;
};
mobileVR.prototype._onOrientationEvent = function(event) {
this.deviceOrientation.alpha = +event.alpha | 0;
this.deviceOrientation.beta = +event.beta | 0;
this.deviceOrientation.gamma = +event.gamma | 0;
};
mobileVR.prototype._startVR = function() {
var _this = this,
alpha = 0,
beta = 0,
gamma = 0;
var deg2Rad = function (degrees) {
return degrees * Math.PI / 180.0;
};
this.vrEnabled = true;
(function loop() {
if (_this.vrEnabled) {
requestAnimationFrame(loop);
}
alpha = deg2Rad(_this.deviceOrientation.alpha); // Y
beta = deg2Rad(_this.deviceOrientation.beta); // Z
// Fix rotation.
gamma = _this.deviceOrientation.gamma; // X
if (gamma < 0)
gamma = deg2Rad(90 + gamma);
else {
gamma = deg2Rad(270 - gamma);
}
_this.rotation.x = gamma;
_this.rotation.y = -alpha;
_this.rotation.z = beta;
// Update the camera
_this._update();
})();
};
return mobileVR;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment