threejs-webvr-point-to-select.html 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. <!-- Licensed under a BSD license. See license.html for license -->
  2. <!DOCTYPE html>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  7. <title>Three.js - WebVR - Point to Select</title>
  8. <style>
  9. body {
  10. margin: 0;
  11. }
  12. #c {
  13. width: 100vw;
  14. height: 100vh;
  15. display: block;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <canvas id="c"></canvas>
  21. </body>
  22. <script type="module">
  23. import * as THREE from './resources/threejs/r114/build/three.module.js';
  24. import {VRButton} from './resources/threejs/r114/examples/jsm/webxr/VRButton.js';
  25. function main() {
  26. const canvas = document.querySelector('#c');
  27. const renderer = new THREE.WebGLRenderer({canvas});
  28. renderer.xr.enabled = true;
  29. document.body.appendChild(VRButton.createButton(renderer));
  30. const fov = 75;
  31. const aspect = 2; // the canvas default
  32. const near = 0.1;
  33. const far = 50;
  34. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  35. camera.position.set(0, 1.6, 0);
  36. const scene = new THREE.Scene();
  37. {
  38. const loader = new THREE.CubeTextureLoader();
  39. const texture = loader.load([
  40. 'resources/images/grid-1024.png',
  41. 'resources/images/grid-1024.png',
  42. 'resources/images/grid-1024.png',
  43. 'resources/images/grid-1024.png',
  44. 'resources/images/grid-1024.png',
  45. 'resources/images/grid-1024.png',
  46. ]);
  47. scene.background = texture;
  48. }
  49. {
  50. const color = 0xFFFFFF;
  51. const intensity = 1;
  52. const light = new THREE.DirectionalLight(color, intensity);
  53. light.position.set(-1, 2, 4);
  54. scene.add(light);
  55. }
  56. const boxWidth = 1;
  57. const boxHeight = 1;
  58. const boxDepth = 1;
  59. const boxGeometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth);
  60. const sphereRadius = 0.5;
  61. const sphereGeometry = new THREE.SphereBufferGeometry(sphereRadius);
  62. function makeInstance(geometry, color, x) {
  63. const material = new THREE.MeshPhongMaterial({color});
  64. const cube = new THREE.Mesh(geometry, material);
  65. scene.add(cube);
  66. cube.position.x = x;
  67. cube.position.y = 1.6;
  68. cube.position.z = -2;
  69. return cube;
  70. }
  71. const meshToMeshMap = new Map();
  72. [
  73. { x: 0, boxColor: 0x44aa88, sphereColor: 0xFF4444, },
  74. { x: 2, boxColor: 0x8844aa, sphereColor: 0x44FF44, },
  75. { x: -2, boxColor: 0xaa8844, sphereColor: 0x4444FF, },
  76. ].forEach((info) => {
  77. const {x, boxColor, sphereColor} = info;
  78. const sphere = makeInstance(sphereGeometry, sphereColor, x);
  79. const box = makeInstance(boxGeometry, boxColor, x);
  80. // hide the sphere
  81. sphere.visible = false;
  82. // map the sphere to the box
  83. meshToMeshMap.set(box, sphere);
  84. // map the box to the sphere
  85. meshToMeshMap.set(sphere, box);
  86. });
  87. class ControllerPickHelper extends THREE.EventDispatcher {
  88. constructor(scene) {
  89. super();
  90. this.raycaster = new THREE.Raycaster();
  91. this.objectToColorMap = new Map();
  92. this.controllerToObjectMap = new Map();
  93. this.tempMatrix = new THREE.Matrix4();
  94. const pointerGeometry = new THREE.BufferGeometry().setFromPoints([
  95. new THREE.Vector3(0, 0, 0),
  96. new THREE.Vector3(0, 0, -1),
  97. ]);
  98. this.controllers = [];
  99. for (let i = 0; i < 2; ++i) {
  100. const controller = renderer.xr.getController(i);
  101. controller.addEventListener('select', (event) => {
  102. const controller = event.target;
  103. const selectedObject = this.controllerToObjectMap.get(controller);
  104. if (selectedObject) {
  105. this.dispatchEvent({type: 'select', controller, selectedObject});
  106. }
  107. });
  108. scene.add(controller);
  109. const line = new THREE.Line(pointerGeometry);
  110. line.scale.z = 5;
  111. controller.add(line);
  112. this.controllers.push({controller, line});
  113. }
  114. }
  115. reset() {
  116. // restore the colors
  117. this.objectToColorMap.forEach((color, object) => {
  118. object.material.emissive.setHex(color);
  119. });
  120. this.objectToColorMap.clear();
  121. this.controllerToObjectMap.clear();
  122. }
  123. update(scene, time) {
  124. this.reset();
  125. for (const {controller, line} of this.controllers) {
  126. // cast a ray through the from the controller
  127. this.tempMatrix.identity().extractRotation(controller.matrixWorld);
  128. this.raycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld);
  129. this.raycaster.ray.direction.set(0, 0, -1).applyMatrix4(this.tempMatrix);
  130. // get the list of objects the ray intersected
  131. const intersections = this.raycaster.intersectObjects(scene.children);
  132. if (intersections.length) {
  133. const intersection = intersections[0];
  134. // make the line touch the object
  135. line.scale.z = intersection.distance;
  136. // pick the first object. It's the closest one
  137. const pickedObject = intersection.object;
  138. // save which object this controller picked
  139. this.controllerToObjectMap.set(controller, pickedObject);
  140. // highlight the object if we haven't already
  141. if (this.objectToColorMap.get(pickedObject) === undefined) {
  142. // save its color
  143. this.objectToColorMap.set(pickedObject, pickedObject.material.emissive.getHex());
  144. // set its emissive color to flashing red/yellow
  145. pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFF2000 : 0xFF0000);
  146. }
  147. } else {
  148. line.scale.z = 5;
  149. }
  150. }
  151. }
  152. }
  153. const pickHelper = new ControllerPickHelper(scene);
  154. pickHelper.addEventListener('select', (event) => {
  155. event.selectedObject.visible = false;
  156. const partnerObject = meshToMeshMap.get(event.selectedObject);
  157. partnerObject.visible = true;
  158. });
  159. function resizeRendererToDisplaySize(renderer) {
  160. const canvas = renderer.domElement;
  161. const width = canvas.clientWidth;
  162. const height = canvas.clientHeight;
  163. const needResize = canvas.width !== width || canvas.height !== height;
  164. if (needResize) {
  165. renderer.setSize(width, height, false);
  166. }
  167. return needResize;
  168. }
  169. function render(time) {
  170. time *= 0.001;
  171. if (resizeRendererToDisplaySize(renderer)) {
  172. const canvas = renderer.domElement;
  173. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  174. camera.updateProjectionMatrix();
  175. }
  176. let ndx = 0;
  177. for (const mesh of meshToMeshMap.keys()) {
  178. const speed = 1 + ndx * .1;
  179. const rot = time * speed;
  180. mesh.rotation.x = rot;
  181. mesh.rotation.y = rot;
  182. ++ndx;
  183. }
  184. pickHelper.update(scene, time);
  185. renderer.render(scene, camera);
  186. }
  187. renderer.setAnimationLoop(render);
  188. }
  189. main();
  190. </script>
  191. </html>