webxr_xr_ballshooter.html 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js xr - ball shooter</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. </head>
  9. <body>
  10. <div id="info">
  11. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> xr - ball shooter
  12. </div>
  13. <script type="importmap">
  14. {
  15. "imports": {
  16. "three": "../build/three.module.js",
  17. "three/addons/": "./jsm/"
  18. }
  19. }
  20. </script>
  21. <script type="module">
  22. import * as THREE from 'three';
  23. import { BoxLineGeometry } from 'three/addons/geometries/BoxLineGeometry.js';
  24. import { XRButton } from 'three/addons/webxr/XRButton.js';
  25. import { XRControllerModelFactory } from 'three/addons/webxr/XRControllerModelFactory.js';
  26. import { RapierPhysics } from 'three/addons/physics/RapierPhysics.js';
  27. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  28. let camera, scene, renderer;
  29. let controller1, controller2;
  30. let controllerGrip1, controllerGrip2;
  31. let room, spheres, physics;
  32. const velocity = new THREE.Vector3();
  33. let count = 0;
  34. init();
  35. await initPhysics();
  36. function init() {
  37. scene = new THREE.Scene();
  38. scene.background = new THREE.Color( 0x505050 );
  39. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.1, 50 );
  40. camera.position.set( 0, 1.6, 3 );
  41. room = new THREE.LineSegments(
  42. new BoxLineGeometry( 6, 6, 6, 10, 10, 10 ),
  43. new THREE.LineBasicMaterial( { color: 0x808080 } )
  44. );
  45. room.geometry.translate( 0, 3, 0 );
  46. scene.add( room );
  47. scene.add( new THREE.HemisphereLight( 0xbbbbbb, 0x888888, 3 ) );
  48. const light = new THREE.DirectionalLight( 0xffffff, 3 );
  49. light.position.set( 1, 1, 1 ).normalize();
  50. scene.add( light );
  51. //
  52. renderer = new THREE.WebGLRenderer( { antialias: true } );
  53. renderer.setPixelRatio( window.devicePixelRatio );
  54. renderer.setSize( window.innerWidth, window.innerHeight );
  55. renderer.setAnimationLoop( animate );
  56. renderer.xr.enabled = true;
  57. document.body.appendChild( renderer.domElement );
  58. //
  59. const controls = new OrbitControls( camera, renderer.domElement );
  60. controls.maxDistance = 10;
  61. controls.target.y = 1.6;
  62. controls.update();
  63. document.body.appendChild( XRButton.createButton( renderer, {
  64. 'optionalFeatures': [ 'depth-sensing' ],
  65. 'depthSensing': { 'usagePreference': [ 'gpu-optimized' ], 'dataFormatPreference': [] }
  66. } ) );
  67. // controllers
  68. function onSelectStart() {
  69. this.userData.isSelecting = true;
  70. }
  71. function onSelectEnd() {
  72. this.userData.isSelecting = false;
  73. }
  74. controller1 = renderer.xr.getController( 0 );
  75. controller1.addEventListener( 'selectstart', onSelectStart );
  76. controller1.addEventListener( 'selectend', onSelectEnd );
  77. controller1.addEventListener( 'connected', function ( event ) {
  78. this.add( buildController( event.data ) );
  79. } );
  80. controller1.addEventListener( 'disconnected', function () {
  81. this.remove( this.children[ 0 ] );
  82. } );
  83. scene.add( controller1 );
  84. controller2 = renderer.xr.getController( 1 );
  85. controller2.addEventListener( 'selectstart', onSelectStart );
  86. controller2.addEventListener( 'selectend', onSelectEnd );
  87. controller2.addEventListener( 'connected', function ( event ) {
  88. this.add( buildController( event.data ) );
  89. } );
  90. controller2.addEventListener( 'disconnected', function () {
  91. this.remove( this.children[ 0 ] );
  92. } );
  93. scene.add( controller2 );
  94. // The XRControllerModelFactory will automatically fetch controller models
  95. // that match what the user is holding as closely as possible. The models
  96. // should be attached to the object returned from getControllerGrip in
  97. // order to match the orientation of the held device.
  98. const controllerModelFactory = new XRControllerModelFactory();
  99. controllerGrip1 = renderer.xr.getControllerGrip( 0 );
  100. controllerGrip1.add( controllerModelFactory.createControllerModel( controllerGrip1 ) );
  101. scene.add( controllerGrip1 );
  102. controllerGrip2 = renderer.xr.getControllerGrip( 1 );
  103. controllerGrip2.add( controllerModelFactory.createControllerModel( controllerGrip2 ) );
  104. scene.add( controllerGrip2 );
  105. //
  106. window.addEventListener( 'resize', onWindowResize );
  107. }
  108. function buildController( data ) {
  109. let geometry, material;
  110. switch ( data.targetRayMode ) {
  111. case 'tracked-pointer':
  112. geometry = new THREE.BufferGeometry();
  113. geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 0, 0, - 1 ], 3 ) );
  114. geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( [ 0.5, 0.5, 0.5, 0, 0, 0 ], 3 ) );
  115. material = new THREE.LineBasicMaterial( { vertexColors: true, blending: THREE.AdditiveBlending } );
  116. return new THREE.Line( geometry, material );
  117. case 'gaze':
  118. geometry = new THREE.RingGeometry( 0.02, 0.04, 32 ).translate( 0, 0, - 1 );
  119. material = new THREE.MeshBasicMaterial( { opacity: 0.5, transparent: true } );
  120. return new THREE.Mesh( geometry, material );
  121. }
  122. }
  123. function onWindowResize() {
  124. camera.aspect = window.innerWidth / window.innerHeight;
  125. camera.updateProjectionMatrix();
  126. renderer.setSize( window.innerWidth, window.innerHeight );
  127. }
  128. async function initPhysics() {
  129. physics = await RapierPhysics();
  130. {
  131. // Floor
  132. const geometry = new THREE.BoxGeometry( 6, 2, 6 );
  133. const material = new THREE.MeshNormalMaterial( { visible: false } );
  134. const floor = new THREE.Mesh( geometry, material );
  135. floor.position.y = - 1;
  136. floor.userData.physics = { mass: 0 };
  137. scene.add( floor );
  138. // Walls
  139. const wallPX = new THREE.Mesh( geometry, material );
  140. wallPX.position.set( 4, 3, 0 );
  141. wallPX.rotation.z = Math.PI / 2;
  142. wallPX.userData.physics = { mass: 0 };
  143. scene.add( wallPX );
  144. const wallNX = new THREE.Mesh( geometry, material );
  145. wallNX.position.set( - 4, 3, 0 );
  146. wallNX.rotation.z = Math.PI / 2;
  147. wallNX.userData.physics = { mass: 0 };
  148. scene.add( wallNX );
  149. const wallPZ = new THREE.Mesh( geometry, material );
  150. wallPZ.position.set( 0, 3, 4 );
  151. wallPZ.rotation.x = Math.PI / 2;
  152. wallPZ.userData.physics = { mass: 0 };
  153. scene.add( wallPZ );
  154. const wallNZ = new THREE.Mesh( geometry, material );
  155. wallNZ.position.set( 0, 3, - 4 );
  156. wallNZ.rotation.x = Math.PI / 2;
  157. wallNZ.userData.physics = { mass: 0 };
  158. scene.add( wallNZ );
  159. }
  160. // Spheres
  161. const geometry = new THREE.IcosahedronGeometry( 0.08, 3 );
  162. const material = new THREE.MeshLambertMaterial();
  163. spheres = new THREE.InstancedMesh( geometry, material, 800 );
  164. spheres.instanceMatrix.setUsage( THREE.DynamicDrawUsage ); // will be updated every frame
  165. spheres.userData.physics = { mass: 1, restitution: 1.1 };
  166. scene.add( spheres );
  167. const matrix = new THREE.Matrix4();
  168. const color = new THREE.Color();
  169. for ( let i = 0; i < spheres.count; i ++ ) {
  170. const x = Math.random() * 4 - 2;
  171. const y = Math.random() * 4;
  172. const z = Math.random() * 4 - 2;
  173. matrix.setPosition( x, y, z );
  174. spheres.setMatrixAt( i, matrix );
  175. spheres.setColorAt( i, color.setHex( 0xffffff * Math.random() ) );
  176. }
  177. physics.addScene( scene );
  178. }
  179. //
  180. function handleController( controller ) {
  181. if ( controller.userData.isSelecting ) {
  182. physics.setMeshPosition( spheres, controller.position, count );
  183. velocity.x = ( Math.random() - 0.5 ) * 2;
  184. velocity.y = ( Math.random() - 0.5 ) * 2;
  185. velocity.z = ( Math.random() - 9 );
  186. velocity.applyQuaternion( controller.quaternion );
  187. physics.setMeshVelocity( spheres, velocity, count );
  188. if ( ++ count === spheres.count ) count = 0;
  189. }
  190. }
  191. function animate() {
  192. handleController( controller1 );
  193. handleController( controller2 );
  194. renderer.render( scene, camera );
  195. }
  196. </script>
  197. </body>
  198. </html>