threejs-game-player-input.html 15 KB

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