FirstPersonControls.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. import {
  2. Controls,
  3. MathUtils,
  4. Spherical,
  5. Vector3
  6. } from 'three';
  7. const _lookDirection = new Vector3();
  8. const _spherical = new Spherical();
  9. const _target = new Vector3();
  10. const _targetPosition = new Vector3();
  11. const _targetVelocity = new Vector3();
  12. /**
  13. * This class is an alternative implementation of {@link FlyControls}.
  14. *
  15. * @augments Controls
  16. * @three_import import { FirstPersonControls } from 'three/addons/controls/FirstPersonControls.js';
  17. */
  18. class FirstPersonControls extends Controls {
  19. /**
  20. * Constructs a new controls instance.
  21. *
  22. * @param {Object3D} object - The object that is managed by the controls.
  23. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  24. */
  25. constructor( object, domElement = null ) {
  26. super( object, domElement );
  27. /**
  28. * The movement speed.
  29. *
  30. * @type {number}
  31. * @default 1
  32. */
  33. this.movementSpeed = 1.0;
  34. /**
  35. * The look around speed.
  36. *
  37. * @type {number}
  38. * @default 0.005
  39. */
  40. this.lookSpeed = 0.005;
  41. /**
  42. * How quickly the movement and look velocity catches up to the input. Lower
  43. * values feel heavier (more inertia), `1` disables damping.
  44. *
  45. * @type {number}
  46. * @default 0.1
  47. */
  48. this.dampingFactor = 0.1;
  49. /**
  50. * Whether it's possible to vertically look around or not.
  51. *
  52. * @type {boolean}
  53. * @default true
  54. */
  55. this.lookVertical = true;
  56. /**
  57. * Whether the camera is automatically moved forward or not.
  58. *
  59. * @type {boolean}
  60. * @default false
  61. */
  62. this.autoForward = false;
  63. /**
  64. * Whether or not the camera's height influences the forward movement speed.
  65. * Use the properties `heightCoef`, `heightMin` and `heightMax` for configuration.
  66. *
  67. * @type {boolean}
  68. * @default false
  69. */
  70. this.heightSpeed = false;
  71. /**
  72. * Determines how much faster the camera moves when it's y-component is near `heightMax`.
  73. *
  74. * @type {number}
  75. * @default 1
  76. */
  77. this.heightCoef = 1.0;
  78. /**
  79. * Lower camera height limit used for movement speed adjustment.
  80. *
  81. * @type {number}
  82. * @default 0
  83. */
  84. this.heightMin = 0.0;
  85. /**
  86. * Upper camera height limit used for movement speed adjustment.
  87. *
  88. * @type {number}
  89. * @default 1
  90. */
  91. this.heightMax = 1.0;
  92. /**
  93. * Whether or not looking around is vertically constrained by `verticalMin` and `verticalMax`.
  94. *
  95. * @type {boolean}
  96. * @default false
  97. */
  98. this.constrainVertical = false;
  99. /**
  100. * How far you can vertically look around, lower limit. Range is `0` to `Math.PI` in radians.
  101. *
  102. * @type {number}
  103. * @default 0
  104. */
  105. this.verticalMin = 0;
  106. /**
  107. * How far you can vertically look around, upper limit. Range is `0` to `Math.PI` in radians.
  108. *
  109. * @type {number}
  110. * @default 0
  111. */
  112. this.verticalMax = Math.PI;
  113. /**
  114. * Whether the mouse is pressed down or not.
  115. *
  116. * @type {boolean}
  117. * @readonly
  118. * @default false
  119. */
  120. this.mouseDragOn = false;
  121. // internals
  122. this._velocity = new Vector3();
  123. this._pointerX = 0;
  124. this._pointerY = 0;
  125. this._pointerDownX = 0;
  126. this._pointerDownY = 0;
  127. this._pointerCount = 0;
  128. // forward / backward come from keys and the pointer, tracked per source so they don't
  129. // clobber: while a forward / backward key is held, a click only looks
  130. this._keyForward = false;
  131. this._keyBackward = false;
  132. this._pointerForward = false;
  133. this._pointerBackward = false;
  134. this._moveLeft = false;
  135. this._moveRight = false;
  136. this._moveUp = false;
  137. this._moveDown = false;
  138. this._lat = 0;
  139. this._lon = 0;
  140. this._lonVelocity = 0;
  141. this._latVelocity = 0;
  142. // event listeners
  143. this._onPointerMove = onPointerMove.bind( this );
  144. this._onPointerDown = onPointerDown.bind( this );
  145. this._onPointerUp = onPointerUp.bind( this );
  146. this._onContextMenu = onContextMenu.bind( this );
  147. this._onKeyDown = onKeyDown.bind( this );
  148. this._onKeyUp = onKeyUp.bind( this );
  149. //
  150. if ( domElement !== null ) {
  151. this.connect( domElement );
  152. }
  153. this._setOrientation();
  154. }
  155. connect( element ) {
  156. super.connect( element );
  157. window.addEventListener( 'keydown', this._onKeyDown );
  158. window.addEventListener( 'keyup', this._onKeyUp );
  159. this.domElement.addEventListener( 'pointerdown', this._onPointerDown );
  160. this.domElement.addEventListener( 'contextmenu', this._onContextMenu );
  161. const { ownerDocument } = this.domElement;
  162. ownerDocument.addEventListener( 'pointermove', this._onPointerMove );
  163. ownerDocument.addEventListener( 'pointerup', this._onPointerUp );
  164. ownerDocument.addEventListener( 'pointercancel', this._onPointerUp );
  165. this.domElement.style.touchAction = 'none'; // Disable touch scroll
  166. }
  167. disconnect() {
  168. window.removeEventListener( 'keydown', this._onKeyDown );
  169. window.removeEventListener( 'keyup', this._onKeyUp );
  170. this.domElement.removeEventListener( 'pointerdown', this._onPointerDown );
  171. this.domElement.removeEventListener( 'contextmenu', this._onContextMenu );
  172. const { ownerDocument } = this.domElement;
  173. ownerDocument.removeEventListener( 'pointermove', this._onPointerMove );
  174. ownerDocument.removeEventListener( 'pointerup', this._onPointerUp );
  175. ownerDocument.removeEventListener( 'pointercancel', this._onPointerUp );
  176. this.domElement.style.touchAction = ''; // Restore touch scroll
  177. }
  178. dispose() {
  179. this.disconnect();
  180. }
  181. /**
  182. * Rotates the camera towards the defined target position.
  183. *
  184. * @param {number|Vector3} x - The x coordinate of the target position or alternatively a vector representing the target position.
  185. * @param {number} y - The y coordinate of the target position.
  186. * @param {number} z - The z coordinate of the target position.
  187. * @return {FirstPersonControls} A reference to this controls.
  188. */
  189. lookAt( x, y, z ) {
  190. if ( x.isVector3 ) {
  191. _target.copy( x );
  192. } else {
  193. _target.set( x, y, z );
  194. }
  195. this.object.lookAt( _target );
  196. this._setOrientation();
  197. return this;
  198. }
  199. update( delta ) {
  200. if ( this.enabled === false ) return;
  201. let drive = ( this._keyForward ? 1 : 0 ) - ( this._keyBackward ? 1 : 0 );
  202. let lookMove = ( this._pointerForward ? 1 : 0 ) - ( this._pointerBackward ? 1 : 0 );
  203. if ( this.autoForward && drive === 0 && lookMove === 0 ) lookMove = 1;
  204. // faster forward movement the higher the camera is
  205. let forwardSpeed = this.movementSpeed;
  206. if ( this.heightSpeed ) {
  207. const y = MathUtils.clamp( this.object.position.y, this.heightMin, this.heightMax );
  208. forwardSpeed += ( y - this.heightMin ) * this.heightCoef;
  209. }
  210. // target velocity in world space: keys are world axis aligned, moving in the
  211. // XZ plane from the camera's yaw only (Q / E along world Y), while pointer
  212. // and touch input moves along the look direction
  213. const yaw = MathUtils.degToRad( this._lon );
  214. const sinYaw = Math.sin( yaw );
  215. const cosYaw = Math.cos( yaw );
  216. let strafe = ( this._moveRight ? 1 : 0 ) - ( this._moveLeft ? 1 : 0 );
  217. let climb = ( this._moveUp ? 1 : 0 ) - ( this._moveDown ? 1 : 0 );
  218. // normalize combined key input so diagonal movement isn't faster
  219. const keyScale = 1 / Math.max( 1, Math.sqrt( strafe * strafe + climb * climb + drive * drive ) );
  220. strafe *= this.movementSpeed * keyScale;
  221. climb *= this.movementSpeed * keyScale;
  222. drive *= ( drive > 0 ? forwardSpeed : this.movementSpeed ) * keyScale;
  223. _targetVelocity.set(
  224. sinYaw * drive - cosYaw * strafe,
  225. climb,
  226. cosYaw * drive + sinYaw * strafe
  227. );
  228. if ( lookMove !== 0 ) {
  229. _lookDirection.set( 0, 0, - 1 ).applyQuaternion( this.object.quaternion );
  230. _targetVelocity.addScaledVector( _lookDirection, lookMove * ( lookMove > 0 ? forwardSpeed : this.movementSpeed ) );
  231. }
  232. // ease toward the target velocity for smooth acceleration and deceleration
  233. this._velocity.lerp( _targetVelocity, this.dampingFactor );
  234. this.object.position.addScaledVector( this._velocity, delta );
  235. let verticalLookRatio = 1;
  236. if ( this.constrainVertical ) {
  237. verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );
  238. }
  239. // target look velocity, zero when not dragging so the view eases to a stop
  240. const targetLon = this.mouseDragOn ? - this._pointerX * this.lookSpeed : 0;
  241. const targetLat = ( this.mouseDragOn && this.lookVertical ) ? - this._pointerY * this.lookSpeed * verticalLookRatio : 0;
  242. this._lonVelocity = MathUtils.lerp( this._lonVelocity, targetLon, this.dampingFactor );
  243. this._latVelocity = MathUtils.lerp( this._latVelocity, targetLat, this.dampingFactor );
  244. this._lon += this._lonVelocity * delta;
  245. this._lat += this._latVelocity * delta;
  246. this._lat = Math.max( - 85, Math.min( 85, this._lat ) );
  247. let phi = MathUtils.degToRad( 90 - this._lat );
  248. const theta = MathUtils.degToRad( this._lon );
  249. if ( this.constrainVertical ) {
  250. phi = MathUtils.mapLinear( phi, 0, Math.PI, this.verticalMin, this.verticalMax );
  251. }
  252. const position = this.object.position;
  253. _targetPosition.setFromSphericalCoords( 1, phi, theta ).add( position );
  254. this.object.lookAt( _targetPosition );
  255. }
  256. _setOrientation() {
  257. const quaternion = this.object.quaternion;
  258. _lookDirection.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  259. _spherical.setFromVector3( _lookDirection );
  260. this._lat = 90 - MathUtils.radToDeg( _spherical.phi );
  261. this._lon = MathUtils.radToDeg( _spherical.theta );
  262. }
  263. /**
  264. * @deprecated, r184. This method is no longer needed.
  265. */
  266. handleResize() {
  267. console.warn( 'THREE.FirstPersonControls: handleResize() has been removed.' );
  268. }
  269. }
  270. function onPointerDown( event ) {
  271. if ( this.domElement !== document ) {
  272. this.domElement.focus();
  273. }
  274. this.domElement.setPointerCapture( event.pointerId );
  275. this._pointerCount ++;
  276. if ( event.pointerType === 'touch' ) {
  277. this._pointerForward = this._pointerCount === 1;
  278. this._pointerBackward = this._pointerCount >= 2;
  279. } else {
  280. switch ( event.button ) {
  281. case 0: if ( ! this._keyForward && ! this._keyBackward ) this._pointerForward = true; break;
  282. case 2: if ( ! this._keyForward && ! this._keyBackward ) this._pointerBackward = true; break;
  283. }
  284. }
  285. this._pointerDownX = event.pageX;
  286. this._pointerDownY = event.pageY;
  287. this._pointerX = 0;
  288. this._pointerY = 0;
  289. this.mouseDragOn = true;
  290. }
  291. function onPointerUp( event ) {
  292. if ( this.mouseDragOn === false ) return;
  293. this.domElement.releasePointerCapture( event.pointerId );
  294. this._pointerCount --;
  295. if ( event.pointerType === 'touch' ) {
  296. this._pointerForward = this._pointerCount === 1;
  297. this._pointerBackward = false;
  298. } else {
  299. switch ( event.button ) {
  300. case 0: this._pointerForward = false; break;
  301. case 2: this._pointerBackward = false; break;
  302. }
  303. }
  304. this._pointerX = 0;
  305. this._pointerY = 0;
  306. if ( this._pointerCount === 0 ) this.mouseDragOn = false;
  307. }
  308. function onPointerMove( event ) {
  309. if ( this.mouseDragOn === false ) return;
  310. this._pointerX = event.pageX - this._pointerDownX;
  311. this._pointerY = event.pageY - this._pointerDownY;
  312. }
  313. function onKeyDown( event ) {
  314. switch ( event.code ) {
  315. case 'ArrowUp':
  316. case 'KeyW': this._keyForward = true; break;
  317. case 'ArrowLeft':
  318. case 'KeyA': this._moveLeft = true; break;
  319. case 'ArrowDown':
  320. case 'KeyS': this._keyBackward = true; break;
  321. case 'ArrowRight':
  322. case 'KeyD': this._moveRight = true; break;
  323. case 'KeyE': this._moveUp = true; break;
  324. case 'KeyQ': this._moveDown = true; break;
  325. }
  326. }
  327. function onKeyUp( event ) {
  328. switch ( event.code ) {
  329. case 'ArrowUp':
  330. case 'KeyW': this._keyForward = false; break;
  331. case 'ArrowLeft':
  332. case 'KeyA': this._moveLeft = false; break;
  333. case 'ArrowDown':
  334. case 'KeyS': this._keyBackward = false; break;
  335. case 'ArrowRight':
  336. case 'KeyD': this._moveRight = false; break;
  337. case 'KeyE': this._moveUp = false; break;
  338. case 'KeyQ': this._moveDown = false; break;
  339. }
  340. }
  341. function onContextMenu( event ) {
  342. if ( this.enabled === false ) return;
  343. event.preventDefault();
  344. }
  345. export { FirstPersonControls };
粤ICP备19079148号