threejs-webvr-point-to-select-w-move.html 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 w/Move</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/r127/build/three.module.js';
  25. import {VRButton} from './resources/threejs/r127/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. const selectListener = (event) => {
  101. const controller = event.target;
  102. const selectedObject = this.controllerToObjectMap.get(event.target);
  103. if (selectedObject) {
  104. this.dispatchEvent({type: event.type, controller, selectedObject});
  105. }
  106. };
  107. const endListener = (event) => {
  108. const controller = event.target;
  109. this.dispatchEvent({type: event.type, controller});
  110. };
  111. for (let i = 0; i < 2; ++i) {
  112. const controller = renderer.xr.getController(i);
  113. controller.addEventListener('select', selectListener);
  114. controller.addEventListener('selectstart', selectListener);
  115. controller.addEventListener('selectend', endListener);
  116. scene.add(controller);
  117. const line = new THREE.Line(pointerGeometry);
  118. line.scale.z = 5;
  119. controller.add(line);
  120. this.controllers.push({controller, line});
  121. }
  122. }
  123. reset() {
  124. // restore the colors
  125. this.objectToColorMap.forEach((color, object) => {
  126. object.material.emissive.setHex(color);
  127. });
  128. this.objectToColorMap.clear();
  129. this.controllerToObjectMap.clear();
  130. }
  131. update(scene, time) {
  132. this.reset();
  133. for (const {controller, line} of this.controllers) {
  134. // cast a ray through the from the controller
  135. this.tempMatrix.identity().extractRotation(controller.matrixWorld);
  136. this.raycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld);
  137. this.raycaster.ray.direction.set(0, 0, -1).applyMatrix4(this.tempMatrix);
  138. // get the list of objects the ray intersected
  139. const intersections = this.raycaster.intersectObjects(scene.children);
  140. if (intersections.length) {
  141. const intersection = intersections[0];
  142. // make the line touch the object
  143. line.scale.z = intersection.distance;
  144. // pick the first object. It's the closest one
  145. const pickedObject = intersection.object;
  146. // save which object this controller picked
  147. this.controllerToObjectMap.set(controller, pickedObject);
  148. // highlight the object if we haven't already
  149. if (this.objectToColorMap.get(pickedObject) === undefined) {
  150. // save its color
  151. this.objectToColorMap.set(pickedObject, pickedObject.material.emissive.getHex());
  152. // set its emissive color to flashing red/yellow
  153. pickedObject.material.emissive.setHex((time * 8) % 2 > 1 ? 0xFF2000 : 0xFF0000);
  154. }
  155. } else {
  156. line.scale.z = 5;
  157. }
  158. }
  159. }
  160. }
  161. const controllerToSelection = new Map();
  162. const pickHelper = new ControllerPickHelper(scene);
  163. pickHelper.addEventListener('selectstart', (event) => {
  164. const {controller, selectedObject} = event;
  165. const existingSelection = controllerToSelection.get(controller);
  166. if (!existingSelection) {
  167. controllerToSelection.set(controller, {
  168. object: selectedObject,
  169. parent: selectedObject.parent,
  170. });
  171. controller.attach(selectedObject);
  172. }
  173. });
  174. pickHelper.addEventListener('selectend', (event) => {
  175. const {controller} = event;
  176. const selection = controllerToSelection.get(controller);
  177. if (selection) {
  178. controllerToSelection.delete(controller);
  179. selection.parent.attach(selection.object);
  180. }
  181. });
  182. function resizeRendererToDisplaySize(renderer) {
  183. const canvas = renderer.domElement;
  184. const width = canvas.clientWidth;
  185. const height = canvas.clientHeight;
  186. const needResize = canvas.width !== width || canvas.height !== height;
  187. if (needResize) {
  188. renderer.setSize(width, height, false);
  189. }
  190. return needResize;
  191. }
  192. function render(time) {
  193. time *= 0.001;
  194. if (resizeRendererToDisplaySize(renderer)) {
  195. const canvas = renderer.domElement;
  196. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  197. camera.updateProjectionMatrix();
  198. }
  199. let ndx = 0;
  200. for (const mesh of meshToMeshMap.keys()) {
  201. const speed = 1 + ndx * .1;
  202. const rot = time * speed;
  203. mesh.rotation.x = rot;
  204. mesh.rotation.y = rot;
  205. ++ndx;
  206. }
  207. pickHelper.update(scene, time);
  208. renderer.render(scene, camera);
  209. }
  210. renderer.setAnimationLoop(render);
  211. }
  212. main();
  213. </script>
  214. </html>