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

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