webxr_vr_handinput_pressbutton.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js vr - handinput - press button</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> vr - handinput - press button<br />
  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 { VRButton } from 'three/addons/webxr/VRButton.js';
  24. import { XRControllerModelFactory } from 'three/addons/webxr/XRControllerModelFactory.js';
  25. import { OculusHandModel } from 'three/addons/webxr/OculusHandModel.js';
  26. import { createText } from 'three/addons/webxr/Text2D.js';
  27. import { World, System, Component, TagComponent, Types } from 'three/addons/libs/ecsy.module.js';
  28. class Object3D extends Component { }
  29. Object3D.schema = {
  30. object: { type: Types.Ref }
  31. };
  32. class Button extends Component { }
  33. Button.schema = {
  34. // button states: [resting, pressed, fully_pressed, recovering]
  35. currState: { type: Types.String, default: 'resting' },
  36. prevState: { type: Types.String, default: 'resting' },
  37. pressSound: { type: Types.Ref, default: null },
  38. releaseSound: { type: Types.Ref, default: null },
  39. restingY: { type: Types.Number, default: null },
  40. surfaceY: { type: Types.Number, default: null },
  41. recoverySpeed: { type: Types.Number, default: 0.4 },
  42. fullPressDistance: { type: Types.Number, default: null },
  43. action: { type: Types.Ref, default: () => { } }
  44. };
  45. class ButtonSystem extends System {
  46. init( attributes ) {
  47. this.renderer = attributes.renderer;
  48. this.soundAdded = false;
  49. }
  50. execute( /*delta, time*/ ) {
  51. let buttonPressSound, buttonReleaseSound;
  52. if ( this.renderer.xr.getSession() && ! this.soundAdded ) {
  53. const xrCamera = this.renderer.xr.getCamera();
  54. const listener = new THREE.AudioListener();
  55. xrCamera.add( listener );
  56. // create a global audio source
  57. buttonPressSound = new THREE.Audio( listener );
  58. buttonReleaseSound = new THREE.Audio( listener );
  59. // load a sound and set it as the Audio object's buffer
  60. const audioLoader = new THREE.AudioLoader();
  61. audioLoader.load( 'sounds/button-press.ogg', function ( buffer ) {
  62. buttonPressSound.setBuffer( buffer );
  63. } );
  64. audioLoader.load( 'sounds/button-release.ogg', function ( buffer ) {
  65. buttonReleaseSound.setBuffer( buffer );
  66. } );
  67. this.soundAdded = true;
  68. }
  69. this.queries.buttons.results.forEach( entity => {
  70. const button = entity.getMutableComponent( Button );
  71. const buttonMesh = entity.getComponent( Object3D ).object;
  72. // populate restingY
  73. if ( button.restingY == null ) {
  74. button.restingY = buttonMesh.position.y;
  75. }
  76. if ( buttonPressSound ) {
  77. button.pressSound = buttonPressSound;
  78. }
  79. if ( buttonReleaseSound ) {
  80. button.releaseSound = buttonReleaseSound;
  81. }
  82. if ( button.currState == 'fully_pressed' && button.prevState != 'fully_pressed' ) {
  83. if ( button.pressSound ) button.pressSound.play();
  84. button.action();
  85. }
  86. if ( button.currState == 'recovering' && button.prevState != 'recovering' ) {
  87. if ( button.releaseSound ) button.releaseSound.play();
  88. }
  89. // preserve prevState, clear currState
  90. // FingerInputSystem will update currState
  91. button.prevState = button.currState;
  92. button.currState = 'resting';
  93. } );
  94. }
  95. }
  96. ButtonSystem.queries = {
  97. buttons: {
  98. components: [ Button ]
  99. }
  100. };
  101. class Pressable extends TagComponent { }
  102. class FingerInputSystem extends System {
  103. init( attributes ) {
  104. this.hands = attributes.hands;
  105. }
  106. execute( delta/*, time*/ ) {
  107. this.queries.pressable.results.forEach( entity => {
  108. const button = entity.getMutableComponent( Button );
  109. const object = entity.getComponent( Object3D ).object;
  110. const pressingDistances = [];
  111. this.hands.forEach( hand => {
  112. if ( hand && hand.intersectBoxObject( object ) ) {
  113. const pressingPosition = hand.getPointerPosition();
  114. pressingDistances.push( button.surfaceY - object.worldToLocal( pressingPosition ).y );
  115. }
  116. } );
  117. if ( pressingDistances.length == 0 ) { // not pressed this frame
  118. if ( object.position.y < button.restingY ) {
  119. object.position.y += button.recoverySpeed * delta;
  120. button.currState = 'recovering';
  121. } else {
  122. object.position.y = button.restingY;
  123. button.currState = 'resting';
  124. }
  125. } else {
  126. button.currState = 'pressed';
  127. const pressingDistance = Math.max( pressingDistances );
  128. if ( pressingDistance > 0 ) {
  129. object.position.y -= pressingDistance;
  130. }
  131. if ( object.position.y <= button.restingY - button.fullPressDistance ) {
  132. button.currState = 'fully_pressed';
  133. object.position.y = button.restingY - button.fullPressDistance;
  134. }
  135. }
  136. } );
  137. }
  138. }
  139. FingerInputSystem.queries = {
  140. pressable: {
  141. components: [ Pressable ]
  142. }
  143. };
  144. class Rotating extends TagComponent { }
  145. class RotatingSystem extends System {
  146. execute( delta/*, time*/ ) {
  147. this.queries.rotatingObjects.results.forEach( entity => {
  148. const object = entity.getComponent( Object3D ).object;
  149. object.rotation.x += 0.4 * delta;
  150. object.rotation.y += 0.4 * delta;
  151. } );
  152. }
  153. }
  154. RotatingSystem.queries = {
  155. rotatingObjects: {
  156. components: [ Rotating ]
  157. }
  158. };
  159. class HandsInstructionText extends TagComponent { }
  160. class InstructionSystem extends System {
  161. init( attributes ) {
  162. this.controllers = attributes.controllers;
  163. }
  164. execute( /*delta, time*/ ) {
  165. let visible = false;
  166. this.controllers.forEach( controller => {
  167. if ( controller.visible ) {
  168. visible = true;
  169. }
  170. } );
  171. this.queries.instructionTexts.results.forEach( entity => {
  172. const object = entity.getComponent( Object3D ).object;
  173. object.visible = visible;
  174. } );
  175. }
  176. }
  177. InstructionSystem.queries = {
  178. instructionTexts: {
  179. components: [ HandsInstructionText ]
  180. }
  181. };
  182. class OffsetFromCamera extends Component { }
  183. OffsetFromCamera.schema = {
  184. x: { type: Types.Number, default: 0 },
  185. y: { type: Types.Number, default: 0 },
  186. z: { type: Types.Number, default: 0 },
  187. };
  188. class NeedCalibration extends TagComponent { }
  189. class CalibrationSystem extends System {
  190. init( attributes ) {
  191. this.camera = attributes.camera;
  192. this.renderer = attributes.renderer;
  193. }
  194. execute( /*delta, time*/ ) {
  195. this.queries.needCalibration.results.forEach( entity => {
  196. if ( this.renderer.xr.getSession() ) {
  197. const offset = entity.getComponent( OffsetFromCamera );
  198. const object = entity.getComponent( Object3D ).object;
  199. const xrCamera = this.renderer.xr.getCamera();
  200. object.position.x = xrCamera.position.x + offset.x;
  201. object.position.y = xrCamera.position.y + offset.y;
  202. object.position.z = xrCamera.position.z + offset.z;
  203. entity.removeComponent( NeedCalibration );
  204. }
  205. } );
  206. }
  207. }
  208. CalibrationSystem.queries = {
  209. needCalibration: {
  210. components: [ NeedCalibration ]
  211. }
  212. };
  213. const world = new World();
  214. const clock = new THREE.Clock();
  215. let camera, scene, renderer;
  216. init();
  217. function makeButtonMesh( x, y, z, color ) {
  218. const geometry = new THREE.BoxGeometry( x, y, z );
  219. const material = new THREE.MeshPhongMaterial( { color: color } );
  220. const buttonMesh = new THREE.Mesh( geometry, material );
  221. buttonMesh.castShadow = true;
  222. buttonMesh.receiveShadow = true;
  223. return buttonMesh;
  224. }
  225. function init() {
  226. const container = document.createElement( 'div' );
  227. document.body.appendChild( container );
  228. scene = new THREE.Scene();
  229. scene.background = new THREE.Color( 0x444444 );
  230. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.1, 10 );
  231. camera.position.set( 0, 1.2, 0.3 );
  232. scene.add( new THREE.HemisphereLight( 0xcccccc, 0x999999, 3 ) );
  233. const light = new THREE.DirectionalLight( 0xffffff, 3 );
  234. light.position.set( 0, 6, 0 );
  235. light.castShadow = true;
  236. light.shadow.camera.top = 2;
  237. light.shadow.camera.bottom = - 2;
  238. light.shadow.camera.right = 2;
  239. light.shadow.camera.left = - 2;
  240. light.shadow.mapSize.set( 4096, 4096 );
  241. scene.add( light );
  242. renderer = new THREE.WebGLRenderer( { antialias: true } );
  243. renderer.setPixelRatio( window.devicePixelRatio );
  244. renderer.setSize( window.innerWidth, window.innerHeight );
  245. renderer.setAnimationLoop( animate );
  246. renderer.shadowMap.enabled = true;
  247. renderer.xr.enabled = true;
  248. renderer.xr.cameraAutoUpdate = false;
  249. container.appendChild( renderer.domElement );
  250. const sessionInit = {
  251. requiredFeatures: [ 'hand-tracking' ]
  252. };
  253. document.body.appendChild( VRButton.createButton( renderer, sessionInit ) );
  254. // controllers
  255. const controller1 = renderer.xr.getController( 0 );
  256. scene.add( controller1 );
  257. const controller2 = renderer.xr.getController( 1 );
  258. scene.add( controller2 );
  259. const controllerModelFactory = new XRControllerModelFactory();
  260. // Hand 1
  261. const controllerGrip1 = renderer.xr.getControllerGrip( 0 );
  262. controllerGrip1.add( controllerModelFactory.createControllerModel( controllerGrip1 ) );
  263. scene.add( controllerGrip1 );
  264. const hand1 = renderer.xr.getHand( 0 );
  265. const handModel1 = new OculusHandModel( hand1 );
  266. hand1.add( handModel1 );
  267. scene.add( hand1 );
  268. // Hand 2
  269. const controllerGrip2 = renderer.xr.getControllerGrip( 1 );
  270. controllerGrip2.add( controllerModelFactory.createControllerModel( controllerGrip2 ) );
  271. scene.add( controllerGrip2 );
  272. const hand2 = renderer.xr.getHand( 1 );
  273. const handModel2 = new OculusHandModel( hand2 );
  274. hand2.add( handModel2 );
  275. scene.add( hand2 );
  276. // buttons
  277. const floorGeometry = new THREE.PlaneGeometry( 4, 4 );
  278. const floorMaterial = new THREE.MeshPhongMaterial( { color: 0x222222 } );
  279. const floor = new THREE.Mesh( floorGeometry, floorMaterial );
  280. floor.rotation.x = - Math.PI / 2;
  281. floor.receiveShadow = true;
  282. scene.add( floor );
  283. const consoleGeometry = new THREE.BoxGeometry( 0.5, 0.12, 0.15 );
  284. const consoleMaterial = new THREE.MeshPhongMaterial( { color: 0x595959 } );
  285. const consoleMesh = new THREE.Mesh( consoleGeometry, consoleMaterial );
  286. consoleMesh.position.set( 0, 1, - 0.3 );
  287. consoleMesh.castShadow = true;
  288. consoleMesh.receiveShadow = true;
  289. scene.add( consoleMesh );
  290. const orangeButton = makeButtonMesh( 0.08, 0.1, 0.08, 0xffd3b5 );
  291. orangeButton.position.set( - 0.15, 0.04, 0 );
  292. consoleMesh.add( orangeButton );
  293. const pinkButton = makeButtonMesh( 0.08, 0.1, 0.08, 0xe84a5f );
  294. pinkButton.position.set( - 0.05, 0.04, 0 );
  295. consoleMesh.add( pinkButton );
  296. const resetButton = makeButtonMesh( 0.08, 0.1, 0.08, 0x355c7d );
  297. const resetButtonText = createText( 'reset', 0.03 );
  298. resetButton.add( resetButtonText );
  299. resetButtonText.rotation.x = - Math.PI / 2;
  300. resetButtonText.position.set( 0, 0.051, 0 );
  301. resetButton.position.set( 0.05, 0.04, 0 );
  302. consoleMesh.add( resetButton );
  303. const exitButton = makeButtonMesh( 0.08, 0.1, 0.08, 0xff0000 );
  304. const exitButtonText = createText( 'exit', 0.03 );
  305. exitButton.add( exitButtonText );
  306. exitButtonText.rotation.x = - Math.PI / 2;
  307. exitButtonText.position.set( 0, 0.051, 0 );
  308. exitButton.position.set( 0.15, 0.04, 0 );
  309. consoleMesh.add( exitButton );
  310. const tkGeometry = new THREE.TorusKnotGeometry( 0.5, 0.2, 200, 32 );
  311. const tkMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff } );
  312. tkMaterial.metalness = 0.8;
  313. const torusKnot = new THREE.Mesh( tkGeometry, tkMaterial );
  314. torusKnot.position.set( 0, 1, - 5 );
  315. scene.add( torusKnot );
  316. const instructionText = createText( 'This is a WebXR Hands demo, please explore with hands.', 0.04 );
  317. instructionText.position.set( 0, 1.6, - 0.6 );
  318. scene.add( instructionText );
  319. const exitText = createText( 'Exiting session...', 0.04 );
  320. exitText.position.set( 0, 1.5, - 0.6 );
  321. exitText.visible = false;
  322. scene.add( exitText );
  323. world
  324. .registerComponent( Object3D )
  325. .registerComponent( Button )
  326. .registerComponent( Pressable )
  327. .registerComponent( Rotating )
  328. .registerComponent( HandsInstructionText )
  329. .registerComponent( OffsetFromCamera )
  330. .registerComponent( NeedCalibration );
  331. world
  332. .registerSystem( RotatingSystem )
  333. .registerSystem( InstructionSystem, { controllers: [ controllerGrip1, controllerGrip2 ] } )
  334. .registerSystem( CalibrationSystem, { renderer: renderer, camera: camera } )
  335. .registerSystem( ButtonSystem, { renderer: renderer, camera: camera } )
  336. .registerSystem( FingerInputSystem, { hands: [ handModel1, handModel2 ] } );
  337. const csEntity = world.createEntity();
  338. csEntity.addComponent( OffsetFromCamera, { x: 0, y: - 0.4, z: - 0.3 } );
  339. csEntity.addComponent( NeedCalibration );
  340. csEntity.addComponent( Object3D, { object: consoleMesh } );
  341. const obEntity = world.createEntity();
  342. obEntity.addComponent( Pressable );
  343. obEntity.addComponent( Object3D, { object: orangeButton } );
  344. const obAction = function () {
  345. torusKnot.material.color.setHex( 0xffd3b5 );
  346. };
  347. obEntity.addComponent( Button, { action: obAction, surfaceY: 0.05, fullPressDistance: 0.02 } );
  348. const pbEntity = world.createEntity();
  349. pbEntity.addComponent( Pressable );
  350. pbEntity.addComponent( Object3D, { object: pinkButton } );
  351. const pbAction = function () {
  352. torusKnot.material.color.setHex( 0xe84a5f );
  353. };
  354. pbEntity.addComponent( Button, { action: pbAction, surfaceY: 0.05, fullPressDistance: 0.02 } );
  355. const rbEntity = world.createEntity();
  356. rbEntity.addComponent( Pressable );
  357. rbEntity.addComponent( Object3D, { object: resetButton } );
  358. const rbAction = function () {
  359. torusKnot.material.color.setHex( 0xffffff );
  360. };
  361. rbEntity.addComponent( Button, { action: rbAction, surfaceY: 0.05, fullPressDistance: 0.02 } );
  362. const ebEntity = world.createEntity();
  363. ebEntity.addComponent( Pressable );
  364. ebEntity.addComponent( Object3D, { object: exitButton } );
  365. const ebAction = function () {
  366. exitText.visible = true;
  367. setTimeout( function () {
  368. exitText.visible = false; renderer.xr.getSession().end();
  369. }, 2000 );
  370. };
  371. ebEntity.addComponent( Button, { action: ebAction, surfaceY: 0.05, recoverySpeed: 0.2, fullPressDistance: 0.03 } );
  372. const tkEntity = world.createEntity();
  373. tkEntity.addComponent( Rotating );
  374. tkEntity.addComponent( Object3D, { object: torusKnot } );
  375. const itEntity = world.createEntity();
  376. itEntity.addComponent( HandsInstructionText );
  377. itEntity.addComponent( Object3D, { object: instructionText } );
  378. window.addEventListener( 'resize', onWindowResize );
  379. }
  380. function onWindowResize() {
  381. camera.aspect = window.innerWidth / window.innerHeight;
  382. camera.updateProjectionMatrix();
  383. renderer.setSize( window.innerWidth, window.innerHeight );
  384. }
  385. function animate() {
  386. const delta = clock.getDelta();
  387. const elapsedTime = clock.elapsedTime;
  388. renderer.xr.updateCamera( camera );
  389. world.execute( delta, elapsedTime );
  390. renderer.render( scene, camera );
  391. }
  392. </script>
  393. </body>
  394. </html>
粤ICP备19079148号