WebVRを動かす
vrWebVRとは
Webブラウザ上でVRアプリケーションを動かすためのAPI。 ヘッドマウントディスプレイの動きを3D空間上の動きに変換してくれる。
WebVR API - Web API インターフェイス | MDN
ただし、まだほとんどのブラウザがVR APIをサポートしていないので、 実際はPolyfillで動かすことになる。
動かしてみる
まず、webvr-boilerplateを動かしてみる。
$ npm init
$ npm install node-static
$ git clone https://github.com/borismus/webvr-boilerplate.git
$ cd webvr-boilerplate/ && npm install & cd ..
var static = require('node-static');
var fileServer = new static.Server('./webvr-boilerplate');
require('http').createServer(function (request, response) {
request.addListener('end', function () {
fileServer.serve(request, response);
}).resume();
}).listen(8080);
http://localhost:8080
を見ると箱が回っているのが映る。
ただ、start_modeに3を指定してVRモードにしようとしたところ、
http://localhost:8080/index.html?start_mode=3
PCのChromeから見ると
base.js:191 Uncaught (in promise) Error: VRDisplay is not capable of presenting
というエラーが出てしまった。
Only enable VR mode if there’s a VR device attached or we are running the polyfill on mobile
と書いてあったので、Android端末から見てみたところ Cardboardのマークが出てきて、それを押したら二眼の表示になった。
描画
webvr-boilerplateでは、描画にThree.jsを使っている。
まずシーンやカメラを作る。
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);
で、cameraをTHREE.VRControlsに渡す。この中でVR APIを呼んでいる。
var controls = new THREE.VRControls(camera);
controls.standing = true;
これをupdateしていくことでVRデバイスにcameraが連動するようになっている。
controls.update();
自分でVR APIを呼んでいるところもあって、
Navigator.getVRDisplays()で
VRDisplayを取得し、
VRDisplay.requestAnimationFrame()で、VRDisplayのリフレッシュレートでアニメーションさせるコールバックが呼ばれるようにしている。
このコールバックの中でcontrols.update()を呼んでいる。
function setupStage() {
navigator.getVRDisplays().then(function(displays) {
if (displays.length > 0) {
vrDisplay = displays[0];
if (vrDisplay.stageParameters) {
setStageDimensions(vrDisplay.stageParameters);
}
vrDisplay.requestAnimationFrame(animate);
}
});
}