Three.js与webVR

WebVR如此近 - three.js的WebVR示例程序解析

WebVR如此近 - three.js的WebVR示例程序解析

关于WebVR

最近VR的发展十分吸引人们的眼球,不少同窗应该也心痒痒的想体验VR设备,然而如今的专业硬件价格还比较高,入手一个估计就要吃土了。可是,对于咱们前端开发者来讲,咱们不只能够简单地在手机上进行视觉上的VR体验,还能够立立刻手进行Web端VR应用的开发!html

WebVR是一个实验性的Javascript API,容许HMD(head-mounted displays)链接到web apps,同时可以接受这些设备的位置和动做信息。这让使用Javascript开发VR应用成为可能(固然已经有不少接口API让Javascript做为开发语言了,不过这并不影响咱们为WebVR感到兴奋)。而让咱们可以立马进行预览与体验,移动设备上的chrome已经支持了WebVR并使手机做为一个简易的HMD。手机能够把屏幕分红左右眼视觉并应用手机中的加速度计、陀螺仪等感应器,你须要作的或许就只是买一个cardboard。不说了,我去下单了!前端

cardborad纸盒,一顿食堂饭钱便可入手node

前言

WebVR仍处于w3c的草案阶段,因此开发和体验都须要polyfill。git

这篇解析基于 webvr-boilerplate ,这个示例的做者,任职google的 Boris Smus 同时也编写了 webvr-polyfill 。 three.js examples中也提供了关于VR的控制例子。这里主要经过对代码注释的方式来解读关键的文件。es6

示例的最终效果以下,打开  并把手机放进cardboard便可体验。你也能够在个人github  对照有关的代码和注释github

按照惯例,这篇解析默认你至少有three.js相关的基础知识。有兴趣也能够浏览一下我以前写的 ThreeJS 轻松实现主视觉太阳系漫游 。web

这篇解析中three.js的版本为V76。文中若有各类错误请指出!chrome

 

先从html开始

在示例中只用到了一个index.html。首先meta标签有几个值得注意的:canvas

1 <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0, shrink-to-fit=no">
2 <meta name="mobile-web-app-capable" content="yes">
3 <meta name="apple-mobile-web-app-capable" content="yes" />
4 <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

这几个标签对web app开发的同窗来讲应该是十分熟悉了。其中 shrink-to-fit=no 是Safari的特性,禁止页面经过缩放去适应适口。

接下来在js引用的部分,引用了这几个资源:promise

1 <script src="node_modules/es6-promise/dist/es6-promise.js"></script>

引入的一个promise polyfill;

1 <script src="node_modules/three/three.js"></script>

three.js核心库

1 <script src="node_modules/three/examples/js/controls/VRControls.js"></script> 

从链接的VR设备中得到位置信息并应用在camera对象上,将在下文展开;

 

1 <script src="node_modules/three/examples/js/effects/VREffect.js"></script> 

处理立体视觉和绘制相关,将在下文展开;

1 <script src="node_modules/webvr-polyfill/build/webvr-polyfill.js"></script>

WebVR polyfill,下文简述调用的API option;

1 <script src="build/webvr-manager.js"></script>

界面按钮以及进入/退出VR模式的控制等。


具体的整个项目文件,能够在 这里 查看有关的代码和注释。

VRControls.js - HMD状态感应

这个文件主要对HMD的状态信息进行获取并应用到camera上。例如在手机上显示的时候,手机的旋转倾斜等就会直接做用到camera上。

第一步是获取链接的VR设备,这一步是基本经过WebVR的API进行的:

 
 1 //获取VR设备(做为信息输入源。若有多个则只取第一个)
 2 function gotVRDevices( devices ) {
 3     for ( var i = 0; i < devices.length; i ++ ) {
 4         if ( ( 'VRDisplay' in window && devices[ i ] instanceof VRDisplay ) || ( 'PositionSensorVRDevice' in window && devices[ i ] instanceof PositionSensorVRDevice ) ) {
 5             vrInput = devices[ i ];
 6             break;  // We keep the first we encounter
 7         }
 8     }
 9 
10     if ( !vrInput ) {
11         if ( onError ) onError( 'VR input not available.' );
12     }
13 }
14 //调用WebVR API获取VR设备
15 if ( navigator.getVRDisplays ) {
16     navigator.getVRDisplays().then( gotVRDevices );
17 } else if ( navigator.getVRDevices ) {
18     // Deprecated API.
19     navigator.getVRDevices().then( gotVRDevices );
20 }

而后是三个关于位置的参数:

 1 // the Rift SDK returns the position in meters
 2 // this scale factor allows the user to define how meters
 3 // are converted to scene units.
 4 //Rift SDK返回的位置信息是以米做为单位的。这里能够定义以几倍的缩放比例转换为three.js中的长度。
 5 this.scale = 1;
 6 
 7 // If true will use "standing space" coordinate system where y=0 is the
 8 // floor and x=0, z=0 is the center of the room.
 9 //表示使用者是否站立姿态。当为false时camra会在y=0的位置,而为true时会结合下面的模拟身高来决定camera的y值。
10 //在没法获取用户姿式信息的设备上,须要在调用时直接指定是站姿仍是坐姿。
11 this.standing = false;
12 
13 // Distance from the users eyes to the floor in meters. Used when
14 // standing=true but the VRDisplay doesn't provide stageParameters.
15 //当为站立姿态时,用户的眼睛(camera)的高度(跟若有硬件时返回的单位一致,为米)。这里会受scale的影响。如scale为2时,实际camera的高度就是3.2。
16 this.userHeight = 1.6;

经过WebVR API获取到用户的设备信息,并应用到camera上,是一个持续进行的过程。所以这部分的信息更新会在requestAnimationFrame中不断地调用。

 1 //将在requestAnimationFrame中应用更新
 2 this.update = function () {
 3     if ( vrInput ) {
 4         if ( vrInput.getPose ) {
 5             //方法返回传感器在某一时刻的信息(object)。例如包括时间戳、位置(x,y,z)、线速度、线加速度、角速度、角加速度、方向信息。
 6             var pose = vrInput.getPose();
 7             //orientation 方向
 8             if ( pose.orientation !== null ) {
 9                 //quaternion  四元数
10                 //把设备的方向复制给camera
11                 object.quaternion.fromArray( pose.orientation );
12             }
13             //位置信息
14             if ( pose.position !== null ) {
15                 //一样把设备的位置复制给camera
16                 object.position.fromArray( pose.position );
17             } else {
18                 object.position.set( 0, 0, 0 );
19             }
20 
21         } else {
22             // Deprecated API.
23             var state = vrInput.getState();
24             if ( state.orientation !== null ) {
25                 object.quaternion.copy( state.orientation );
26             }
27             if ( state.position !== null ) {
28                 object.position.copy( state.position );
29             } else {
30                 object.position.set( 0, 0, 0 );
31             }
32         }
33 
34         //TODO 此块会一直执行
35         if ( this.standing ) {
36             //若是硬件返回场景信息,则应用硬件返回的数据来进行站姿转换
37             if ( vrInput.stageParameters ) {
38                 object.updateMatrix();
39                 //sittingToStandingTransform返回一个Matrix4,表示从坐姿到站姿的变换。
40                 standingMatrix.fromArray(vrInput.stageParameters.sittingToStandingTransform);
41                 //应用变换到camera。
42                 object.applyMatrix( standingMatrix );
43             } else {
44                 //若是vrInput不提供y高度信息的话使用userHeight做为高度
45                 object.position.setY( object.position.y + this.userHeight );
46             }
47 
48         }
49         //使用上面定义的this.scale来缩放camera的位置。
50         object.position.multiplyScalar( scope.scale );
51     }
52 };

以上是vrcontrols的关键代码。

VREffect.js - 立体视觉

VREffect.js主要把屏幕显示切割为左右眼所视的屏幕,两个屏幕所显示的内容具备必定的差别,使得人的双目立体视觉能够把屏幕中的内容看得立体化。这个文件主要的流程以下图:

首先是对画布大小进行了设定。其中renderer.setPixelRatio( 1 ); 是防止在retina等屏幕上出现图像变形等显示问题。

 1 //初始化或者resize的时候进行。
 2 this.setSize = function ( width, height ) {
 3     rendererSize = { width: width, height: height };
 4 
 5     //是否VR模式中
 6     if ( isPresenting ) {
 7         //getEyeParameters包含了渲染某个眼睛所视的屏幕的信息,例如offset,FOV等
 8         var eyeParamsL = vrHMD.getEyeParameters( 'left' );
 9         //设备像素比
10         //若设备像素比不为1时会出现显示问题。
11         //https://github.com/mrdoob/three.js/pull/6248
12         renderer.setPixelRatio( 1 );
13 
14         if ( isDeprecatedAPI ) {
15             renderer.setSize( eyeParamsL.renderRect.width * 2, eyeParamsL.renderRect.height, false );
16 
17         } else {
18             renderer.setSize( eyeParamsL.renderWidth * 2, eyeParamsL.renderHeight, false );
19         }
20 
21     } else {
22         renderer.setPixelRatio( rendererPixelRatio );
23         renderer.setSize( width, height );
24     }
25 };

而后是关于全屏模式的设置,这里跟上面的设定差不远:

 1 //显示设备进入全屏显示模式
 2 function onFullscreenChange () {
 3     var wasPresenting = isPresenting;
 4     isPresenting = vrHMD !== undefined && ( vrHMD.isPresenting || ( isDeprecatedAPI && document[ fullscreenElement ] instanceof window.HTMLElement ) );
 5     if ( wasPresenting === isPresenting ) {
 6         return;
 7     }
 8 
 9     //若是这次事件是进入VR模式
10     if ( isPresenting ) {
11         rendererPixelRatio = renderer.getPixelRatio();
12         rendererSize = renderer.getSize();
13 
14         //getEyeParameters包含了渲染某个眼睛所视的屏幕的信息,例如offset,FOV等
15         var eyeParamsL = vrHMD.getEyeParameters( 'left' );
16         var eyeWidth, eyeHeight;
17 
18         if ( isDeprecatedAPI ) {
19             eyeWidth = eyeParamsL.renderRect.width;
20             eyeHeight = eyeParamsL.renderRect.height;
21         } else {
22             eyeWidth = eyeParamsL.renderWidth;
23             eyeHeight = eyeParamsL.renderHeight;
24         }
25         renderer.setPixelRatio( 1 );
26         renderer.setSize( eyeWidth * 2, eyeHeight, false );
27 
28     } else {
29         renderer.setPixelRatio( rendererPixelRatio );
30         renderer.setSize( rendererSize.width, rendererSize.height );
31     }
32 }

接下来是对表示左右眼的camera的设定。两个camera也确定是PerspectiveCamera:

1 var cameraL = new THREE.PerspectiveCamera();
2 //左camera显示layer 1层(即当某个元素只出如今layer 1时,只有cameraL可见。)
3 cameraL.layers.enable( 1 );
4 
5 var cameraR = new THREE.PerspectiveCamera();
6 cameraR.layers.enable( 2 );

从WebVR API中获取关于某个眼睛所视的屏幕的信息:

 1 //getEyeParameters包含了渲染某个眼睛所视的屏幕的信息,例如offset,FOV等
 2 var eyeParamsL = vrHMD.getEyeParameters( 'left' );
 3 var eyeParamsR = vrHMD.getEyeParameters( 'right' );
 4 
 5 if ( ! isDeprecatedAPI ) {
 6     // represents the offset from the center point between the user's eyes to the center of the eye, measured in meters.
 7     //瞳距的偏移
 8     eyeTranslationL.fromArray( eyeParamsL.offset );
 9     eyeTranslationR.fromArray( eyeParamsR.offset );
10     //represents a field of view defined by 4 different degree values describing the view from a center point.
11     //得到左右眼的FOV
12     eyeFOVL = eyeParamsL.fieldOfView;
13     eyeFOVR = eyeParamsR.fieldOfView;
14 
15 } else {
16     eyeTranslationL.copy( eyeParamsL.eyeTranslation );
17     eyeTranslationR.copy( eyeParamsR.eyeTranslation );
18     eyeFOVL = eyeParamsL.recommendedFieldOfView;
19     eyeFOVR = eyeParamsR.recommendedFieldOfView;
20 }
21 
22 if ( Array.isArray( scene ) ) {
23     console.warn( 'THREE.VREffect.render() no longer supports arrays. Use object.layers instead.' );
24     scene = scene[ 0 ];
25 }

因为左右camera的视锥体还没肯定,须要对得到的FOV信息进行计算来肯定。在涉及透视投影矩阵的部分会比较复杂,因此这里不展开来讲。若是有错误请指出:

 1 cameraL.projectionMatrix = fovToProjection( eyeFOVL, true, camera.near, camera.far );
 2 cameraR.projectionMatrix = fovToProjection( eyeFOVR, true, camera.near, camera.far );
 3 
 4 //角度弧度的转换,而后进行后续的计算
 5 function fovToProjection( fov, rightHanded, zNear, zFar ) {
 6     //角度转换为弧度  如30度转为1/6 PI
 7     var DEG2RAD = Math.PI / 180.0;
 8 
 9     var fovPort = {
10         upTan: Math.tan( fov.upDegrees * DEG2RAD ),
11         downTan: Math.tan( fov.downDegrees * DEG2RAD ),
12         leftTan: Math.tan( fov.leftDegrees * DEG2RAD ),
13         rightTan: Math.tan( fov.rightDegrees * DEG2RAD )
14     };
15 
16     return fovPortToProjection( fovPort, rightHanded, zNear, zFar );
17 }
18 
19 //根据从设备得到的FOV以及相机设定的near、far来生成透视投影矩阵
20 function fovPortToProjection( fov, rightHanded, zNear, zFar ) {
21 
22     //使用右手坐标
23     rightHanded = rightHanded === undefined ? true : rightHanded;
24     zNear = zNear === undefined ? 0.01 : zNear;
25     zFar = zFar === undefined ? 10000.0 : zFar;
26 
27     var handednessScale = rightHanded ? - 1.0 : 1.0;
28 
29     // start with an identity matrix
30 
31     var mobj = new THREE.Matrix4();
32     var m = mobj.elements;
33 
34     // and with scale/offset info for normalized device coords
35     var scaleAndOffset = fovToNDCScaleOffset( fov );
36 
37     //创建透视投影矩阵
38 
39     // X result, map clip edges to [-w,+w]
40     m[ 0 * 4 + 0 ] = scaleAndOffset.scale[ 0 ];
41     m[ 0 * 4 + 1 ] = 0.0;
42     m[ 0 * 4 + 2 ] = scaleAndOffset.offset[ 0 ] * handednessScale;
43     m[ 0 * 4 + 3 ] = 0.0;
44 
45     // Y result, map clip edges to [-w,+w]
46     // Y offset is negated because this proj matrix transforms from world coords with Y=up,
47     // but the NDC scaling has Y=down (thanks D3D?)
48     //NDC(归一化设备坐标系)是左手坐标系
49     m[ 1 * 4 + 0 ] = 0.0;
50     m[ 1 * 4 + 1 ] = scaleAndOffset.scale[ 1 ];
51     m[ 1 * 4 + 2 ] = - scaleAndOffset.offset[ 1 ] * handednessScale;
52     m[ 1 * 4 + 3 ] = 0.0;
53 
54     // Z result (up to the app)
55     m[ 2 * 4 + 0 ] = 0.0;
56     m[ 2 * 4 + 1 ] = 0.0;
57     m[ 2 * 4 + 2 ] = zFar / ( zNear - zFar ) * - handednessScale;
58     m[ 2 * 4 + 3 ] = ( zFar * zNear ) / ( zNear - zFar );
59 
60     // W result (= Z in)
61     m[ 3 * 4 + 0 ] = 0.0;
62     m[ 3 * 4 + 1 ] = 0.0;
63     m[ 3 * 4 + 2 ] = handednessScale;
64     m[ 3 * 4 + 3 ] = 0.0;
65 
66     //转置矩阵,由于mobj.elements是column-major的
67     mobj.transpose();
68 
69     return mobj;
70 }
71 
72 //计算线性插值信息
73 function fovToNDCScaleOffset( fov ) {
74 
75     var pxscale = 2.0 / ( fov.leftTan + fov.rightTan );
76     var pxoffset = ( fov.leftTan - fov.rightTan ) * pxscale * 0.5;
77     var pyscale = 2.0 / ( fov.upTan + fov.downTan );
78     var pyoffset = ( fov.upTan - fov.downTan ) * pyscale * 0.5;
79     return { scale: [ pxscale, pyscale ], offset: [ pxoffset, pyoffset ] };
80 }

以后是肯定左右camera的位置和方向。因为左右眼(左右camera)确定是在头部(主camera,位置和方向由HMD返回的信息肯定)上的,在咱们得到把眼睛从头部飞出去的超能力以前,左右camera的位置和方向都是根据主camera来设定的。

1 //使主camera的位移、旋转、缩放变换分解,做用到左camra 右camera上。
2 camera.matrixWorld.decompose( cameraL.position, cameraL.quaternion, cameraL.scale );
3 camera.matrixWorld.decompose( cameraR.position, cameraR.quaternion, cameraR.scale );
4 
5 var scale = this.scale;
6 //左右眼camera根据瞳距进行位移。
7 cameraL.translateOnAxis( eyeTranslationL, scale );
8 cameraR.translateOnAxis( eyeTranslationR, scale );

最后即是对两个区域进行渲染。

1 // 渲染左眼视觉
2 renderer.setViewport( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
3 renderer.setScissor( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
4 renderer.render( scene, cameraL );
5 
6 // 渲染右眼视觉
7 renderer.setViewport( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
8 renderer.setScissor( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
9 renderer.render( scene, cameraR );

VREffect文件的关键点差很少是上述这些。

webvr-polyfill.js - 让如今使用WebVR成为可能

webvr-polyfill.js 根据WebVR API的草案来实现了一套polyfill。例如根据所处环境是pc仍是手机来肯定使用的是 CardboardVRDisplay 仍是 MouseKeyboardVRDisplay ,在手机环境下的话使用 Device API 来处理手机旋转、方向等参数的获取。此外做者还顺便作了几个提示图标和画面来优化体验。在这里咱们来看一下其API参数:

 1 WebVRConfig = {
 2   /**
 3    * webvr-polyfill configuration
 4    */
 5 
 6   // Flag to disabled the UI in VR Mode.
 7   //是否禁用VR模式的UI。
 8   CARDBOARD_UI_DISABLED: false, // Default: false
 9 
10   // Forces availability of VR mode.
11   //是否强制使VR模式可用。
12   //FORCE_ENABLE_VR: true, // Default: false.
13 
14   // Complementary filter coefficient. 0 for accelerometer, 1 for gyro.
15   //互补滤波系数。加速度计在静止的时候是很准的,但运动时的角度噪声很大,陀螺仪反之。
16   //互补滤波器徘徊在信任陀螺仪和加速度计的边界。首先选择一个时间常数,而后用它来计算滤波器系数。
17   //例如陀螺仪的漂移是每秒2度,则可能须要一个少于一秒的时间常数去保证在每个方向上的漂移不会超过2度。
18   //可是当时间常数越低,越多加速度计的噪声将容许经过。因此这是一个权衡的内容。
19   //K_FILTER: 0.98, // Default: 0.98.
20 
21   // Flag to disable the instructions to rotate your device.
22   //是否禁用旋转设备的提示(横放手机以进入全屏)。
23   ROTATE_INSTRUCTIONS_DISABLED: false, // Default: false
24 
25   // How far into the future to predict during fast motion.
26   //因为有给定的方向以及陀螺仪信息,选择容许预测多长时间以内的设备方向,在设备快速移动的状况下可让渲染比较流畅。
27   //PREDICTION_TIME_S: 0.040, // Default: 0.040 (in seconds).
28 
29   // Flag to disable touch panner. In case you have your own touch controls、
30   //是否禁用提供的触摸控制,当你有本身的触摸控制方式时能够禁用
31   //TOUCH_PANNER_DISABLED: true, // Default: false.
32 
33   // To disable keyboard and mouse controls, if you want to use your own
34   // implementation.
35   //是否禁用pc下的鼠标、键盘控制。同上。
36   //MOUSE_KEYBOARD_CONTROLS_DISABLED: true, // Default: false.
37 
38   // Enable yaw panning only, disabling roll and pitch. This can be useful for
39   // panoramas with nothing interesting above or below.
40   // 仅关心左右角度变化,忽略上下和倾斜等。
41   // YAW_ONLY: true, // Default: false.
42 
43   // Prevent the polyfill from initializing immediately. Requires the app
44   // to call InitializeWebVRPolyfill() before it can be used.
45   //是否阻止组件直接进行初始化构建。若是为true则须要本身调用InitializeWebVRPolyfill()。
46   //DEFER_INITIALIZATION: true, // Default: false.
47 
48   // Enable the deprecated version of the API (navigator.getVRDevices).
49   //容许使用过期版本的API。
50   //ENABLE_DEPRECATED_API: true, // Default: false.
51 
52   // Scales the recommended buffer size reported by WebVR, which can improve
53   // performance. Making this very small can lower the effective resolution of
54   // your scene.
55   //在VR显示模式下对WebVR推荐的屏幕比例进行缩放。在IOS下若是不为0.5会出现显示问题,查看
56   //https://github.com/borismus/webvr-polyfill/pull/106
57   BUFFER_SCALE: 0.5, // default: 1.0
58 
59   // Allow VRDisplay.submitFrame to change gl bindings, which is more
60   // efficient if the application code will re-bind it's resources on the
61   // next frame anyway.
62   // Dirty bindings include: gl.FRAMEBUFFER_BINDING, gl.CURRENT_PROGRAM,
63   // gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING,
64   // and gl.TEXTURE_BINDING_2D for texture unit 0
65   // Warning: enabling this might lead to rendering issues.
66   //容许 VRDisplay.submitFrame使用脏矩形渲染。可是开启此特性可能会出现渲染问题。
67   //DIRTY_SUBMIT_FRAME_BINDINGS: true // default: false
68 };

其config主要是对一些用户可选项进行设定。在文件内部,更多的是对 Device API 的应用等等。

如今就开始编写WebVR应用吧!

在示例的最后是一个显示简单的旋转立方体的demo。此处能够帮助咱们学习怎么建立一个WebVR应用。

首先是创建好scene、renderer、camera的三要素:

 1 // Setup three.js WebGL renderer. Note: Antialiasing is a big performance hit.
 2 // Only enable it if you actually need to.
 3 var renderer = new THREE.WebGLRenderer({antialias: true});
 4 renderer.setPixelRatio(window.devicePixelRatio);
 5 
 6 // Append the canvas element created by the renderer to document body element.
 7 document.body.appendChild(renderer.domElement);
 8 
 9 // Create a three.js scene.
10 var scene = new THREE.Scene();
11 
12 // Create a three.js camera.
13 var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);

对上面解析过的controls、effect进行调用:

 1 // Apply VR headset positional data to camera.
 2 var controls = new THREE.VRControls(camera);
 3 //站立姿态
 4 controls.standing = true;
 5 
 6 // Apply VR stereo rendering to renderer.
 7 var effect = new THREE.VREffect(renderer);
 8 effect.setSize(window.innerWidth, window.innerHeight);
 9 
10 // Create a VR manager helper to enter and exit VR mode.
11 //按钮和全屏模式管理
12 var params = {
13   hideButton: false, // Default: false.
14   isUndistorted: false // Default: false.
15 };
16 var manager = new WebVRManager(renderer, effect, params);

在场景中,添加一个网格显示的空间,在空间内加入一个小立方体:

 1 // Add a repeating grid as a skybox.
 2 var boxSize = 5;
 3 var loader = new THREE.TextureLoader();
 4 loader.load('img/box.png', onTextureLoaded);
 5 
 6 function onTextureLoaded(texture) {
 7   texture.wrapS = THREE.RepeatWrapping;
 8   texture.wrapT = THREE.RepeatWrapping;
 9   texture.repeat.set(boxSize, boxSize);
10 
11   var geometry = new THREE.BoxGeometry(boxSize, boxSize, boxSize);
12   var material = new THREE.MeshBasicMaterial({
13     map: texture,
14     color: 0x01BE00,
15     side: THREE.BackSide
16   });
17 
18   // Align the skybox to the floor (which is at y=0).
19   skybox = new THREE.Mesh(geometry, material);
20   skybox.position.y = boxSize/2;
21   scene.add(skybox);
22 
23   // For high end VR devices like Vive and Oculus, take into account the stage
24   // parameters provided.
25   //在高端的设备上,要考虑到设备提供的场景信息的更新。
26   setupStage();
27 }
28 
29 // Create 3D objects.
30 var geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
31 var material = new THREE.MeshNormalMaterial();
32 var cube = new THREE.Mesh(geometry, material);
33 
34 // Position cube mesh to be right in front of you.
35 cube.position.set(0, controls.userHeight, -1);
36 
37 scene.add(cube);

最后即是设置requestAnimationFrame的更新。在animate的函数中,不但要考虑立方体的旋转问题,更重要的是要不断地获取HMD返回的信息以及对camera进行更新。

 

 
 1 // Request animation frame loop function
 2 var lastRender = 0;
 3 function animate(timestamp) {
 4   var delta = Math.min(timestamp - lastRender, 500);
 5   lastRender = timestamp;
 6 
 7   //立方体的旋转
 8   cube.rotation.y += delta * 0.0006;
 9 
10   // Update VR headset position and apply to camera.
11   //更新获取HMD的信息
12   controls.update();
13 
14   // Render the scene through the manager.
15   //进行camera更新和场景绘制
16   manager.render(scene, camera, timestamp);
17 
18   requestAnimationFrame(animate);
19 }

总结

以上即是此示例的各个文件的解析。我相信VR的形式除了在游戏上的应用的前景,在其余方面也有其值得探索的可行性。因此让咱们一块儿来开始WebVR之旅吧!

相关文章
相关标签/搜索