game-player-input.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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 - Game - Player Input</title>
  8. <style>
  9. html {
  10. box-sizing: border-box;
  11. }
  12. *, *:before, *:after {
  13. box-sizing: inherit;
  14. }
  15. html, body {
  16. margin: 0;
  17. height: 100%;
  18. user-select: none;
  19. }
  20. img, canvas {
  21. /* prevent the save-image on long press on mobile */
  22. pointer-events: none;
  23. }
  24. #c {
  25. width: 100%;
  26. height: 100%;
  27. display: block;
  28. }
  29. #ui {
  30. position: absolute;
  31. left: 0;
  32. top: 0;
  33. width: 100%;
  34. height: 100%;
  35. display: flex;
  36. justify-items: center;
  37. align-content: stretch;
  38. }
  39. #ui>div {
  40. display: flex;
  41. align-items: flex-end;
  42. flex: 1 1 auto;
  43. }
  44. .bright {
  45. filter: brightness(2);
  46. }
  47. #left {
  48. justify-content: flex-end;
  49. }
  50. #right {
  51. justify-content: flex-start;
  52. }
  53. #ui img {
  54. padding: 10px;
  55. width: 80px;
  56. height: 80px;
  57. display: block;
  58. }
  59. #loading {
  60. position: absolute;
  61. left: 0;
  62. top: 0;
  63. width: 100%;
  64. height: 100%;
  65. display: flex;
  66. align-items: center;
  67. justify-content: center;
  68. text-align: center;
  69. font-size: xx-large;
  70. font-family: sans-serif;
  71. }
  72. #loading>div>div {
  73. padding: 2px;
  74. }
  75. .progress {
  76. width: 50vw;
  77. border: 1px solid black;
  78. }
  79. #progressbar {
  80. width: 0%;
  81. transition: width ease-out .5s;
  82. height: 1em;
  83. background-color: #888;
  84. background-image: linear-gradient(
  85. -45deg,
  86. rgba(255, 255, 255, .5) 25%,
  87. transparent 25%,
  88. transparent 50%,
  89. rgba(255, 255, 255, .5) 50%,
  90. rgba(255, 255, 255, .5) 75%,
  91. transparent 75%,
  92. transparent
  93. );
  94. background-size: 50px 50px;
  95. animation: progressanim 2s linear infinite;
  96. }
  97. @keyframes progressanim {
  98. 0% {
  99. background-position: 50px 50px;
  100. }
  101. 100% {
  102. background-position: 0 0;
  103. }
  104. }
  105. </style>
  106. </head>
  107. <body>
  108. <canvas id="c" tabindex="1"></canvas>
  109. <div id="ui">
  110. <div id="left"><img src="resources/images/left.svg"></div>
  111. <div style="flex: 0 0 40px;"></div>
  112. <div id="right"><img src="resources/images/right.svg"></div>
  113. </div>
  114. <div id="loading">
  115. <div>
  116. <div>...loading...</div>
  117. <div class="progress"><div id="progressbar"></div></div>
  118. </div>
  119. </div>
  120. </body>
  121. <script type="importmap">
  122. {
  123. "imports": {
  124. "three": "../../build/three.module.js",
  125. "three/addons/": "../../examples/jsm/"
  126. }
  127. }
  128. </script>
  129. <script type="module">
  130. import * as THREE from 'three';
  131. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  132. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  133. import * as SkeletonUtils from 'three/addons/utils/SkeletonUtils.js';
  134. function main() {
  135. const canvas = document.querySelector( '#c' );
  136. const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
  137. const fov = 45;
  138. const aspect = 2; // the canvas default
  139. const near = 0.1;
  140. const far = 1000;
  141. const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  142. camera.position.set( 0, 40, 80 );
  143. const controls = new OrbitControls( camera, canvas );
  144. controls.target.set( 0, 5, 0 );
  145. controls.update();
  146. const scene = new THREE.Scene();
  147. scene.background = new THREE.Color( 'white' );
  148. function addLight( ...pos ) {
  149. const color = 0xFFFFFF;
  150. const intensity = 2.5;
  151. const light = new THREE.DirectionalLight( color, intensity );
  152. light.position.set( ...pos );
  153. scene.add( light );
  154. scene.add( light.target );
  155. }
  156. addLight( 5, 5, 2 );
  157. addLight( - 5, 5, 5 );
  158. const manager = new THREE.LoadingManager();
  159. manager.onLoad = init;
  160. const progressbarElem = document.querySelector( '#progressbar' );
  161. manager.onProgress = ( url, itemsLoaded, itemsTotal ) => {
  162. progressbarElem.style.width = `${itemsLoaded / itemsTotal * 100 | 0}%`;
  163. };
  164. const models = {
  165. pig: { url: 'resources/models/animals/Pig.gltf' },
  166. cow: { url: 'resources/models/animals/Cow.gltf' },
  167. llama: { url: 'resources/models/animals/Llama.gltf' },
  168. pug: { url: 'resources/models/animals/Pug.gltf' },
  169. sheep: { url: 'resources/models/animals/Sheep.gltf' },
  170. zebra: { url: 'resources/models/animals/Zebra.gltf' },
  171. horse: { url: 'resources/models/animals/Horse.gltf' },
  172. knight: { url: 'resources/models/knight/KnightCharacter.gltf' },
  173. };
  174. {
  175. const gltfLoader = new GLTFLoader( manager );
  176. for ( const model of Object.values( models ) ) {
  177. gltfLoader.load( model.url, ( gltf ) => {
  178. model.gltf = gltf;
  179. } );
  180. }
  181. }
  182. function prepModelsAndAnimations() {
  183. Object.values( models ).forEach( model => {
  184. const animsByName = {};
  185. model.gltf.animations.forEach( ( clip ) => {
  186. animsByName[ clip.name ] = clip;
  187. // Should really fix this in .blend file
  188. if ( clip.name === 'Walk' ) {
  189. clip.duration /= 2;
  190. }
  191. } );
  192. model.animations = animsByName;
  193. } );
  194. }
  195. // Keeps the state of keys/buttons
  196. //
  197. // You can check
  198. //
  199. // inputManager.keys.left.down
  200. //
  201. // to see if the left key is currently held down
  202. // and you can check
  203. //
  204. // inputManager.keys.left.justPressed
  205. //
  206. // To see if the left key was pressed this frame
  207. //
  208. // Keys are 'left', 'right', 'a', 'b', 'up', 'down'
  209. class InputManager {
  210. constructor() {
  211. this.keys = {};
  212. const keyMap = new Map();
  213. const setKey = ( keyName, pressed ) => {
  214. const keyState = this.keys[ keyName ];
  215. keyState.justPressed = pressed && ! keyState.down;
  216. keyState.down = pressed;
  217. };
  218. const addKey = ( keyCode, name ) => {
  219. this.keys[ name ] = { down: false, justPressed: false };
  220. keyMap.set( keyCode, name );
  221. };
  222. const setKeyFromKeyCode = ( keyCode, pressed ) => {
  223. const keyName = keyMap.get( keyCode );
  224. if ( ! keyName ) {
  225. return;
  226. }
  227. setKey( keyName, pressed );
  228. };
  229. addKey( 37, 'left' );
  230. addKey( 39, 'right' );
  231. addKey( 38, 'up' );
  232. addKey( 40, 'down' );
  233. addKey( 90, 'a' );
  234. addKey( 88, 'b' );
  235. window.addEventListener( 'keydown', ( e ) => {
  236. setKeyFromKeyCode( e.keyCode, true );
  237. } );
  238. window.addEventListener( 'keyup', ( e ) => {
  239. setKeyFromKeyCode( e.keyCode, false );
  240. } );
  241. const sides = [
  242. { elem: document.querySelector( '#left' ), key: 'left' },
  243. { elem: document.querySelector( '#right' ), key: 'right' },
  244. ];
  245. // note: not a good design?
  246. // The last direction the user presses should take
  247. // precedence. Example: User presses L, without letting go of
  248. // L user presses R. Input should now be R. User lets off R
  249. // Input should now be L.
  250. // With this code if user pressed both L and R result is nothing
  251. const clearKeys = () => {
  252. for ( const { key } of sides ) {
  253. setKey( key, false );
  254. }
  255. };
  256. const handleMouseMove = ( e ) => {
  257. e.preventDefault();
  258. // this is needed because we call preventDefault();
  259. // we also gave the canvas a tabindex so it can
  260. // become the focus
  261. canvas.focus();
  262. window.addEventListener( 'pointermove', handleMouseMove );
  263. window.addEventListener( 'pointerup', handleMouseUp );
  264. for ( const { elem, key } of sides ) {
  265. let pressed = false;
  266. const rect = elem.getBoundingClientRect();
  267. const x = e.clientX;
  268. const y = e.clientY;
  269. const inRect = x >= rect.left && x < rect.right &&
  270. y >= rect.top && y < rect.bottom;
  271. if ( inRect ) {
  272. pressed = true;
  273. }
  274. setKey( key, pressed );
  275. }
  276. };
  277. function handleMouseUp() {
  278. clearKeys();
  279. window.removeEventListener( 'pointermove', handleMouseMove, { passive: false } );
  280. window.removeEventListener( 'pointerup', handleMouseUp );
  281. }
  282. const uiElem = document.querySelector( '#ui' );
  283. uiElem.addEventListener( 'pointerdown', handleMouseMove, { passive: false } );
  284. uiElem.addEventListener( 'touchstart', ( e ) => {
  285. // prevent scrolling
  286. e.preventDefault();
  287. }, { passive: false } );
  288. }
  289. update() {
  290. for ( const keyState of Object.values( this.keys ) ) {
  291. if ( keyState.justPressed ) {
  292. keyState.justPressed = false;
  293. }
  294. }
  295. }
  296. }
  297. function removeArrayElement( array, element ) {
  298. const ndx = array.indexOf( element );
  299. if ( ndx >= 0 ) {
  300. array.splice( ndx, 1 );
  301. }
  302. }
  303. class SafeArray {
  304. constructor() {
  305. this.array = [];
  306. this.addQueue = [];
  307. this.removeQueue = new Set();
  308. }
  309. get isEmpty() {
  310. return this.addQueue.length + this.array.length > 0;
  311. }
  312. add( element ) {
  313. this.addQueue.push( element );
  314. }
  315. remove( element ) {
  316. this.removeQueue.add( element );
  317. }
  318. forEach( fn ) {
  319. this._addQueued();
  320. this._removeQueued();
  321. for ( const element of this.array ) {
  322. if ( this.removeQueue.has( element ) ) {
  323. continue;
  324. }
  325. fn( element );
  326. }
  327. this._removeQueued();
  328. }
  329. _addQueued() {
  330. if ( this.addQueue.length ) {
  331. this.array.splice( this.array.length, 0, ...this.addQueue );
  332. this.addQueue = [];
  333. }
  334. }
  335. _removeQueued() {
  336. if ( this.removeQueue.size ) {
  337. this.array = this.array.filter( element => ! this.removeQueue.has( element ) );
  338. this.removeQueue.clear();
  339. }
  340. }
  341. }
  342. class GameObjectManager {
  343. constructor() {
  344. this.gameObjects = new SafeArray();
  345. }
  346. createGameObject( parent, name ) {
  347. const gameObject = new GameObject( parent, name );
  348. this.gameObjects.add( gameObject );
  349. return gameObject;
  350. }
  351. removeGameObject( gameObject ) {
  352. this.gameObjects.remove( gameObject );
  353. }
  354. update() {
  355. this.gameObjects.forEach( gameObject => gameObject.update() );
  356. }
  357. }
  358. const kForward = new THREE.Vector3( 0, 0, 1 );
  359. const globals = {
  360. time: 0,
  361. deltaTime: 0,
  362. moveSpeed: 16,
  363. camera,
  364. };
  365. const gameObjectManager = new GameObjectManager();
  366. const inputManager = new InputManager();
  367. class GameObject {
  368. constructor( parent, name ) {
  369. this.name = name;
  370. this.components = [];
  371. this.transform = new THREE.Object3D();
  372. parent.add( this.transform );
  373. }
  374. addComponent( ComponentType, ...args ) {
  375. const component = new ComponentType( this, ...args );
  376. this.components.push( component );
  377. return component;
  378. }
  379. removeComponent( component ) {
  380. removeArrayElement( this.components, component );
  381. }
  382. getComponent( ComponentType ) {
  383. return this.components.find( c => c instanceof ComponentType );
  384. }
  385. update() {
  386. for ( const component of this.components ) {
  387. component.update();
  388. }
  389. }
  390. }
  391. // Base for all components
  392. class Component {
  393. constructor( gameObject ) {
  394. this.gameObject = gameObject;
  395. }
  396. update() {
  397. }
  398. }
  399. class CameraInfo extends Component {
  400. constructor( gameObject ) {
  401. super( gameObject );
  402. this.projScreenMatrix = new THREE.Matrix4();
  403. this.frustum = new THREE.Frustum();
  404. }
  405. update() {
  406. const { camera } = globals;
  407. this.projScreenMatrix.multiplyMatrices(
  408. camera.projectionMatrix,
  409. camera.matrixWorldInverse );
  410. this.frustum.setFromProjectionMatrix( this.projScreenMatrix );
  411. }
  412. }
  413. class SkinInstance extends Component {
  414. constructor( gameObject, model ) {
  415. super( gameObject );
  416. this.model = model;
  417. this.animRoot = SkeletonUtils.clone( this.model.gltf.scene );
  418. this.mixer = new THREE.AnimationMixer( this.animRoot );
  419. gameObject.transform.add( this.animRoot );
  420. this.actions = {};
  421. }
  422. setAnimation( animName ) {
  423. const clip = this.model.animations[ animName ];
  424. // turn off all current actions
  425. for ( const action of Object.values( this.actions ) ) {
  426. action.enabled = false;
  427. }
  428. // get or create existing action for clip
  429. const action = this.mixer.clipAction( clip );
  430. action.enabled = true;
  431. action.reset();
  432. action.play();
  433. this.actions[ animName ] = action;
  434. }
  435. update() {
  436. this.mixer.update( globals.deltaTime );
  437. }
  438. }
  439. class Player extends Component {
  440. constructor( gameObject ) {
  441. super( gameObject );
  442. const model = models.knight;
  443. this.skinInstance = gameObject.addComponent( SkinInstance, model );
  444. this.skinInstance.setAnimation( 'Run' );
  445. this.turnSpeed = globals.moveSpeed / 4;
  446. this.offscreenTimer = 0;
  447. this.maxTimeOffScreen = 3;
  448. }
  449. update() {
  450. const { deltaTime, moveSpeed } = globals;
  451. const { transform } = this.gameObject;
  452. const delta = ( inputManager.keys.left.down ? 1 : 0 ) +
  453. ( inputManager.keys.right.down ? - 1 : 0 );
  454. transform.rotation.y += this.turnSpeed * delta * deltaTime;
  455. transform.translateOnAxis( kForward, moveSpeed * deltaTime );
  456. const { frustum } = globals.cameraInfo;
  457. if ( frustum.containsPoint( transform.position ) ) {
  458. this.offscreenTimer = 0;
  459. } else {
  460. this.offscreenTimer += deltaTime;
  461. if ( this.offscreenTimer >= this.maxTimeOffScreen ) {
  462. transform.position.set( 0, 0, 0 );
  463. }
  464. }
  465. }
  466. }
  467. function init() {
  468. // hide the loading bar
  469. const loadingElem = document.querySelector( '#loading' );
  470. loadingElem.style.display = 'none';
  471. prepModelsAndAnimations();
  472. {
  473. const gameObject = gameObjectManager.createGameObject( camera, 'camera' );
  474. globals.cameraInfo = gameObject.addComponent( CameraInfo );
  475. }
  476. {
  477. const gameObject = gameObjectManager.createGameObject( scene, 'player' );
  478. gameObject.addComponent( Player );
  479. }
  480. }
  481. function resizeRendererToDisplaySize( renderer ) {
  482. const canvas = renderer.domElement;
  483. const width = canvas.clientWidth;
  484. const height = canvas.clientHeight;
  485. const needResize = canvas.width !== width || canvas.height !== height;
  486. if ( needResize ) {
  487. renderer.setSize( width, height, false );
  488. }
  489. return needResize;
  490. }
  491. let then = 0;
  492. function render( now ) {
  493. // convert to seconds
  494. globals.time = now * 0.001;
  495. // make sure delta time isn't too big.
  496. globals.deltaTime = Math.min( globals.time - then, 1 / 20 );
  497. then = globals.time;
  498. if ( resizeRendererToDisplaySize( renderer ) ) {
  499. const canvas = renderer.domElement;
  500. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  501. camera.updateProjectionMatrix();
  502. }
  503. gameObjectManager.update();
  504. inputManager.update();
  505. renderer.render( scene, camera );
  506. requestAnimationFrame( render );
  507. }
  508. requestAnimationFrame( render );
  509. }
  510. main();
  511. </script>
  512. </html>