webxr-point-to-select.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. <!DOCTYPE html><html lang="en"><head>
  2. <meta charset="utf-8">
  3. <title>VR - 3DOF Point to Select</title>
  4. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  5. <meta name="twitter:card" content="summary_large_image">
  6. <meta name="twitter:site" content="@threejs">
  7. <meta name="twitter:title" content="Three.js – VR - 3DOF Point to Select">
  8. <meta property="og:image" content="https://threejs.org/files/share.png">
  9. <link rel="shortcut icon" href="../../files/favicon_white.ico" media="(prefers-color-scheme: dark)">
  10. <link rel="shortcut icon" href="../../files/favicon.ico" media="(prefers-color-scheme: light)">
  11. <link rel="stylesheet" href="../resources/lesson.css">
  12. <link rel="stylesheet" href="../resources/lang.css">
  13. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../../build/three.module.js"
  17. }
  18. }
  19. </script>
  20. </head>
  21. <body>
  22. <div class="container">
  23. <div class="lesson-title">
  24. <h1>VR - 3DOF Point to Select</h1>
  25. </div>
  26. <div class="lesson">
  27. <div class="lesson-main">
  28. <p><strong>NOTE: The examples on this page require a VR capable
  29. device with a pointing device. Without one they won't work. See <a href="webxr.html">this article</a>
  30. as to why</strong></p>
  31. <p>In the <a href="webxr-look-to-select.html">previous article</a> we went over
  32. a very simple VR example where we let the user choose things by
  33. pointing via looking. In this article we will take it one step further
  34. and let the user choose with a pointing device </p>
  35. <p>Three.js makes is relatively easy by providing 2 controller objects in VR
  36. and tries to handle both cases of a single 3DOF controller and two 6DOF
  37. controllers. Each of the controllers are <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a> objects which give
  38. the orientation and position of that controller. They also provide
  39. <code class="notranslate" translate="no">selectstart</code>, <code class="notranslate" translate="no">select</code> and <code class="notranslate" translate="no">selectend</code> events when the user starts pressing,
  40. is pressing, and stops pressing (ends) the "main" button on the controller.</p>
  41. <p>Starting with the last example from <a href="webxr-look-to-select.html">the previous article</a>
  42. let's change the <code class="notranslate" translate="no">PickHelper</code> into a <code class="notranslate" translate="no">ControllerPickHelper</code>.</p>
  43. <p>Our new implementation will emit a <code class="notranslate" translate="no">select</code> event that gives us the object that was picked
  44. so to use it we'll just need to do this.</p>
  45. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const pickHelper = new ControllerPickHelper(scene);
  46. pickHelper.addEventListener('select', (event) =&gt; {
  47. event.selectedObject.visible = false;
  48. const partnerObject = meshToMeshMap.get(event.selectedObject);
  49. partnerObject.visible = true;
  50. });
  51. </pre>
  52. <p>Remember from our previous code <code class="notranslate" translate="no">meshToMeshMap</code> maps our boxes and spheres to
  53. each other so if we have one we can look up its partner through <code class="notranslate" translate="no">meshToMeshMap</code>
  54. so here we're just hiding the selected object and un-hiding its partner.</p>
  55. <p>As for the actual implementation of <code class="notranslate" translate="no">ControllerPickHelper</code>, first we need
  56. to add the VR controller objects to the scene and to those add some 3D lines
  57. we can use to display where the user is pointing. We save off both the controllers
  58. and the their lines.</p>
  59. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ControllerPickHelper {
  60. constructor(scene) {
  61. const pointerGeometry = new THREE.BufferGeometry().setFromPoints([
  62. new THREE.Vector3(0, 0, 0),
  63. new THREE.Vector3(0, 0, -1),
  64. ]);
  65. this.controllers = [];
  66. for (let i = 0; i &lt; 2; ++i) {
  67. const controller = renderer.xr.getController(i);
  68. scene.add(controller);
  69. const line = new THREE.Line(pointerGeometry);
  70. line.scale.z = 5;
  71. controller.add(line);
  72. this.controllers.push({controller, line});
  73. }
  74. }
  75. }
  76. </pre>
  77. <p>Without doing anything else this alone would give us 1 or 2 lines in the scene
  78. showing where the user's pointing devices are and which way they are pointing.</p>
  79. <p>One problem we have though, we don't want have our <code class="notranslate" translate="no">RayCaster</code> pick the line itself
  80. so an easy solution is separate the objects we wanted to be able to pick from the
  81. objects we don't by parenting them under another <a href="/docs/#api/en/core/Object3D"><code class="notranslate" translate="no">Object3D</code></a>.</p>
  82. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const scene = new THREE.Scene();
  83. +// object to put pickable objects on so we can easily
  84. +// separate them from non-pickable objects
  85. +const pickRoot = new THREE.Object3D();
  86. +scene.add(pickRoot);
  87. ...
  88. function makeInstance(geometry, color, x) {
  89. const material = new THREE.MeshPhongMaterial({color});
  90. const cube = new THREE.Mesh(geometry, material);
  91. - scene.add(cube);
  92. + pickRoot.add(cube);
  93. ...
  94. </pre>
  95. <p>Next let's add some code to pick from the controllers. This is the first time
  96. we've picked with something not the camera. In our <a href="picking.html">article on picking</a>
  97. the user uses the mouse or finger to pick which means picking comes from the camera
  98. into the screen. In <a href="webxr-look-to-select.html">the previous article</a> we
  99. were picking based on which way the user is looking so again that comes from the
  100. camera. This time though we're picking from the position of the controllers so
  101. we're not using the camera.</p>
  102. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ControllerPickHelper {
  103. constructor(scene) {
  104. + this.raycaster = new THREE.Raycaster();
  105. + this.objectToColorMap = new Map();
  106. + this.controllerToObjectMap = new Map();
  107. + this.tempMatrix = new THREE.Matrix4();
  108. const pointerGeometry = new THREE.BufferGeometry().setFromPoints([
  109. new THREE.Vector3(0, 0, 0),
  110. new THREE.Vector3(0, 0, -1),
  111. ]);
  112. this.controllers = [];
  113. for (let i = 0; i &lt; 2; ++i) {
  114. const controller = renderer.xr.getController(i);
  115. scene.add(controller);
  116. const line = new THREE.Line(pointerGeometry);
  117. line.scale.z = 5;
  118. controller.add(line);
  119. this.controllers.push({controller, line});
  120. }
  121. }
  122. + update(pickablesParent, time) {
  123. + this.reset();
  124. + for (const {controller, line} of this.controllers) {
  125. + // cast a ray through the from the controller
  126. + this.tempMatrix.identity().extractRotation(controller.matrixWorld);
  127. + this.raycaster.ray.origin.setFromMatrixPosition(controller.matrixWorld);
  128. + this.raycaster.ray.direction.set(0, 0, -1).applyMatrix4(this.tempMatrix);
  129. + // get the list of objects the ray intersected
  130. + const intersections = this.raycaster.intersectObjects(pickablesParent.children);
  131. + if (intersections.length) {
  132. + const intersection = intersections[0];
  133. + // make the line touch the object
  134. + line.scale.z = intersection.distance;
  135. + // pick the first object. It's the closest one
  136. + const pickedObject = intersection.object;
  137. + // save which object this controller picked
  138. + this.controllerToObjectMap.set(controller, pickedObject);
  139. + // highlight the object if we haven't already
  140. + if (this.objectToColorMap.get(pickedObject) === undefined) {
  141. + // save its color
  142. + this.objectToColorMap.set(pickedObject, pickedObject.material.emissive.getHex());
  143. + // set its emissive color to flashing red/yellow
  144. + pickedObject.material.emissive.setHex((time * 8) % 2 &gt; 1 ? 0xFF2000 : 0xFF0000);
  145. + }
  146. + } else {
  147. + line.scale.z = 5;
  148. + }
  149. + }
  150. + }
  151. }
  152. </pre>
  153. <p>Like before we use a <a href="/docs/#api/en/core/Raycaster"><code class="notranslate" translate="no">Raycaster</code></a> but this time we take the ray from the controller.
  154. Our previous <code class="notranslate" translate="no">PickHelper</code> there was only one thing picking but here we have up to 2
  155. controllers, one for each hand. We save off which object each controller is
  156. looking at in <code class="notranslate" translate="no">controllerToObjectMap</code>. We also save off the original emissive color in
  157. <code class="notranslate" translate="no">objectToColorMap</code> and we make the line long enough to touch whatever it's pointing at.</p>
  158. <p>We need to add some code to reset these settings every frame.</p>
  159. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ControllerPickHelper {
  160. ...
  161. + _reset() {
  162. + // restore the colors
  163. + this.objectToColorMap.forEach((color, object) =&gt; {
  164. + object.material.emissive.setHex(color);
  165. + });
  166. + this.objectToColorMap.clear();
  167. + this.controllerToObjectMap.clear();
  168. + }
  169. update(pickablesParent, time) {
  170. + this._reset();
  171. ...
  172. }
  173. </pre>
  174. <p>Next we want to emit a <code class="notranslate" translate="no">select</code> event when the user clicks the controller.
  175. To do that we can extend three.js's <a href="/docs/#api/en/core/EventDispatcher"><code class="notranslate" translate="no">EventDispatcher</code></a> and then we'll check
  176. when we get a <code class="notranslate" translate="no">select</code> event from the controller, then if that controller
  177. is pointing at something we emit what that controller is pointing at
  178. as our own <code class="notranslate" translate="no">select</code> event.</p>
  179. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">-class ControllerPickHelper {
  180. +class ControllerPickHelper extends THREE.EventDispatcher {
  181. constructor(scene) {
  182. + super();
  183. this.raycaster = new THREE.Raycaster();
  184. this.objectToColorMap = new Map(); // object to save color and picked object
  185. this.controllerToObjectMap = new Map();
  186. this.tempMatrix = new THREE.Matrix4();
  187. const pointerGeometry = new THREE.BufferGeometry().setFromPoints([
  188. new THREE.Vector3(0, 0, 0),
  189. new THREE.Vector3(0, 0, -1),
  190. ]);
  191. this.controllers = [];
  192. for (let i = 0; i &lt; 2; ++i) {
  193. const controller = renderer.xr.getController(i);
  194. + controller.addEventListener('select', (event) =&gt; {
  195. + const controller = event.target;
  196. + const selectedObject = this.controllerToObjectMap.get(controller);
  197. + if (selectedObject) {
  198. + this.dispatchEvent({type: 'select', controller, selectedObject});
  199. + }
  200. + });
  201. scene.add(controller);
  202. const line = new THREE.Line(pointerGeometry);
  203. line.scale.z = 5;
  204. controller.add(line);
  205. this.controllers.push({controller, line});
  206. }
  207. }
  208. }
  209. </pre>
  210. <p>All that is left is to call <code class="notranslate" translate="no">update</code> in our render loop</p>
  211. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">function render(time) {
  212. ...
  213. + pickHelper.update(pickablesParent, time);
  214. renderer.render(scene, camera);
  215. }
  216. </pre>
  217. <p>and assuming you have a VR device with a controller you should
  218. be able to use the controllers to pick things.</p>
  219. <p></p><div translate="no" class="threejs_example_container notranslate">
  220. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/webxr-point-to-select.html"></iframe></div>
  221. <a class="threejs_center" href="/manual/examples/webxr-point-to-select.html" target="_blank">click here to open in a separate window</a>
  222. </div>
  223. <p></p>
  224. <p>And what if we wanted to be able to move the objects?</p>
  225. <p>That's relatively easy. Let's move our controller 'select' listener
  226. code out into a function so we can use it for more than one thing.</p>
  227. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ControllerPickHelper extends THREE.EventDispatcher {
  228. constructor(scene) {
  229. super();
  230. ...
  231. this.controllers = [];
  232. + const selectListener = (event) =&gt; {
  233. + const controller = event.target;
  234. + const selectedObject = this.controllerToObjectMap.get(event.target);
  235. + if (selectedObject) {
  236. + this.dispatchEvent({type: 'select', controller, selectedObject});
  237. + }
  238. + };
  239. for (let i = 0; i &lt; 2; ++i) {
  240. const controller = renderer.xr.getController(i);
  241. - controller.addEventListener('select', (event) =&gt; {
  242. - const controller = event.target;
  243. - const selectedObject = this.controllerToObjectMap.get(event.target);
  244. - if (selectedObject) {
  245. - this.dispatchEvent({type: 'select', controller, selectedObject});
  246. - }
  247. - });
  248. + controller.addEventListener('select', selectListener);
  249. ...
  250. </pre>
  251. <p>Then let's use it for both <code class="notranslate" translate="no">selectstart</code> and <code class="notranslate" translate="no">select</code></p>
  252. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ControllerPickHelper extends THREE.EventDispatcher {
  253. constructor(scene) {
  254. super();
  255. ...
  256. this.controllers = [];
  257. const selectListener = (event) =&gt; {
  258. const controller = event.target;
  259. const selectedObject = this.controllerToObjectMap.get(event.target);
  260. if (selectedObject) {
  261. - this.dispatchEvent({type: 'select', controller, selectedObject});
  262. + this.dispatchEvent({type: event.type, controller, selectedObject});
  263. }
  264. };
  265. for (let i = 0; i &lt; 2; ++i) {
  266. const controller = renderer.xr.getController(i);
  267. controller.addEventListener('select', selectListener);
  268. controller.addEventListener('selectstart', selectListener);
  269. ...
  270. </pre>
  271. <p>and let's also pass on the <code class="notranslate" translate="no">selectend</code> event which three.js sends out
  272. when you user lets of the button on the controller.</p>
  273. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">class ControllerPickHelper extends THREE.EventDispatcher {
  274. constructor(scene) {
  275. super();
  276. ...
  277. this.controllers = [];
  278. const selectListener = (event) =&gt; {
  279. const controller = event.target;
  280. const selectedObject = this.controllerToObjectMap.get(event.target);
  281. if (selectedObject) {
  282. this.dispatchEvent({type: event.type, controller, selectedObject});
  283. }
  284. };
  285. + const endListener = (event) =&gt; {
  286. + const controller = event.target;
  287. + this.dispatchEvent({type: event.type, controller});
  288. + };
  289. for (let i = 0; i &lt; 2; ++i) {
  290. const controller = renderer.xr.getController(i);
  291. controller.addEventListener('select', selectListener);
  292. controller.addEventListener('selectstart', selectListener);
  293. + controller.addEventListener('selectend', endListener);
  294. ...
  295. </pre>
  296. <p>Now let's change the code so when we get a <code class="notranslate" translate="no">selectstart</code> event we'll
  297. remove the selected object from the scene and make it a child of the controller.
  298. This means it will move with the controller. When we get a <code class="notranslate" translate="no">selectend</code>
  299. event we'll put it back in the scene.</p>
  300. <pre class="prettyprint showlinemods notranslate lang-js" translate="no">const pickHelper = new ControllerPickHelper(scene);
  301. -pickHelper.addEventListener('select', (event) =&gt; {
  302. - event.selectedObject.visible = false;
  303. - const partnerObject = meshToMeshMap.get(event.selectedObject);
  304. - partnerObject.visible = true;
  305. -});
  306. +const controllerToSelection = new Map();
  307. +pickHelper.addEventListener('selectstart', (event) =&gt; {
  308. + const {controller, selectedObject} = event;
  309. + const existingSelection = controllerToSelection.get(controller);
  310. + if (!existingSelection) {
  311. + controllerToSelection.set(controller, {
  312. + object: selectedObject,
  313. + parent: selectedObject.parent,
  314. + });
  315. + controller.attach(selectedObject);
  316. + }
  317. +});
  318. +
  319. +pickHelper.addEventListener('selectend', (event) =&gt; {
  320. + const {controller} = event;
  321. + const selection = controllerToSelection.get(controller);
  322. + if (selection) {
  323. + controllerToSelection.delete(controller);
  324. + selection.parent.attach(selection.object);
  325. + }
  326. +});
  327. </pre>
  328. <p>When an object is selected we save off that object and its
  329. original parent. When the user is done we can put the object back.</p>
  330. <p>We use the <a href="/docs/#api/en/core/Object3D.attach"><code class="notranslate" translate="no">Object3D.attach</code></a> to re-parent
  331. the selected objects. These functions let us change the parent
  332. of an object without changing its orientation and position in the
  333. scene. </p>
  334. <p>And with that we should be able to move the objects around with a 6DOF
  335. controller or at least change their orientation with a 3DOF controller</p>
  336. <p></p><div translate="no" class="threejs_example_container notranslate">
  337. <div><iframe class="threejs_example notranslate" translate="no" style=" " src="/manual/examples/resources/editor.html?url=/manual/examples/webxr-point-to-select-w-move.html"></iframe></div>
  338. <a class="threejs_center" href="/manual/examples/webxr-point-to-select-w-move.html" target="_blank">click here to open in a separate window</a>
  339. </div>
  340. <p></p>
  341. <p>To be honest I'm not 100% sure this <code class="notranslate" translate="no">ControllerPickHelper</code> is
  342. the best way to organize the code but it's useful to demonstrating
  343. the various parts of getting something simple working in VR
  344. in three.js</p>
  345. </div>
  346. </div>
  347. </div>
  348. <script src="../resources/prettify.js"></script>
  349. <script src="../resources/lesson.js"></script>
  350. </body></html>