threejs-game-player-input.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. // this is needed because we call preventDefault();
  286. // we also gave the canvas a tabindex so it can
  287. // become the focus
  288. canvas.focus();
  289. handleMouseMove(e);
  290. window.addEventListener('mousemove', handleMouseMove);
  291. window.addEventListener('mouseup', handleMouseUp);
  292. }, {passive: false});
  293. }
  294. update() {
  295. for (const keyState of Object.values(this.keys)) {
  296. if (keyState.justPressed) {
  297. keyState.justPressed = false;
  298. }
  299. }
  300. }
  301. }
  302. function removeArrayElement(array, element) {
  303. const ndx = array.indexOf(element);
  304. if (ndx >= 0) {
  305. array.splice(ndx, 1);
  306. }
  307. }
  308. class SafeArray {
  309. constructor() {
  310. this.array = [];
  311. this.addQueue = [];
  312. this.removeQueue = new Set();
  313. }
  314. get isEmpty() {
  315. return this.addQueue.length + this.array.length > 0;
  316. }
  317. add(element) {
  318. this.addQueue.push(element);
  319. }
  320. remove(element) {
  321. this.removeQueue.add(element);
  322. }
  323. forEach(fn) {
  324. this._addQueued();
  325. this._removeQueued();
  326. for (const element of this.array) {
  327. if (this.removeQueue.has(element)) {
  328. continue;
  329. }
  330. fn(element);
  331. }
  332. this._removeQueued();
  333. }
  334. _addQueued() {
  335. if (this.addQueue.length) {
  336. this.array.splice(this.array.length, 0, ...this.addQueue);
  337. this.addQueue = [];
  338. }
  339. }
  340. _removeQueued() {
  341. if (this.removeQueue.size) {
  342. this.array = this.array.filter(element => !this.removeQueue.has(element));
  343. this.removeQueue.clear();
  344. }
  345. }
  346. }
  347. class GameObjectManager {
  348. constructor() {
  349. this.gameObjects = new SafeArray();
  350. }
  351. createGameObject(parent, name) {
  352. const gameObject = new GameObject(parent, name);
  353. this.gameObjects.add(gameObject);
  354. return gameObject;
  355. }
  356. removeGameObject(gameObject) {
  357. this.gameObjects.remove(gameObject);
  358. }
  359. update() {
  360. this.gameObjects.forEach(gameObject => gameObject.update());
  361. }
  362. }
  363. const kForward = new THREE.Vector3(0, 0, 1);
  364. const globals = {
  365. time: 0,
  366. deltaTime: 0,
  367. moveSpeed: 16,
  368. camera,
  369. };
  370. const gameObjectManager = new GameObjectManager();
  371. const inputManager = new InputManager();
  372. class GameObject {
  373. constructor(parent, name) {
  374. this.name = name;
  375. this.components = [];
  376. this.transform = new THREE.Object3D();
  377. parent.add(this.transform);
  378. }
  379. addComponent(ComponentType, ...args) {
  380. const component = new ComponentType(this, ...args);
  381. this.components.push(component);
  382. return component;
  383. }
  384. removeComponent(component) {
  385. removeArrayElement(this.components, component);
  386. }
  387. getComponent(ComponentType) {
  388. return this.components.find(c => c instanceof ComponentType);
  389. }
  390. update() {
  391. for (const component of this.components) {
  392. component.update();
  393. }
  394. }
  395. }
  396. // Base for all components
  397. class Component {
  398. constructor(gameObject) {
  399. this.gameObject = gameObject;
  400. }
  401. update() {
  402. }
  403. }
  404. class CameraInfo extends Component {
  405. constructor(gameObject) {
  406. super(gameObject);
  407. this.projScreenMatrix = new THREE.Matrix4();
  408. this.frustum = new THREE.Frustum();
  409. }
  410. update() {
  411. const {camera} = globals;
  412. this.projScreenMatrix.multiplyMatrices(
  413. camera.projectionMatrix,
  414. camera.matrixWorldInverse);
  415. this.frustum.setFromMatrix(this.projScreenMatrix);
  416. }
  417. }
  418. class SkinInstance extends Component {
  419. constructor(gameObject, model) {
  420. super(gameObject);
  421. this.model = model;
  422. this.animRoot = THREE.SkeletonUtils.clone(this.model.gltf.scene);
  423. this.mixer = new THREE.AnimationMixer(this.animRoot);
  424. gameObject.transform.add(this.animRoot);
  425. this.actions = {};
  426. }
  427. setAnimation(animName) {
  428. const clip = this.model.animations[animName];
  429. // turn off all current actions
  430. for (const action of Object.values(this.actions)) {
  431. action.enabled = false;
  432. }
  433. // get or create existing action for clip
  434. const action = this.mixer.clipAction(clip);
  435. action.enabled = true;
  436. action.reset();
  437. action.play();
  438. this.actions[animName] = action;
  439. }
  440. update() {
  441. this.mixer.update(globals.deltaTime);
  442. }
  443. }
  444. class Player extends Component {
  445. constructor(gameObject) {
  446. super(gameObject);
  447. const model = models.knight;
  448. this.skinInstance = gameObject.addComponent(SkinInstance, model);
  449. this.skinInstance.setAnimation('Run');
  450. this.turnSpeed = globals.moveSpeed / 4;
  451. this.offscreenTimer = 0;
  452. this.maxTimeOffScreen = 3;
  453. }
  454. update() {
  455. const {deltaTime, moveSpeed} = globals;
  456. const {transform} = this.gameObject;
  457. const delta = (inputManager.keys.left.down ? 1 : 0) +
  458. (inputManager.keys.right.down ? -1 : 0);
  459. transform.rotation.y += this.turnSpeed * delta * deltaTime;
  460. transform.translateOnAxis(kForward, moveSpeed * deltaTime);
  461. const {frustum} = globals.cameraInfo;
  462. if (frustum.containsPoint(transform.position)) {
  463. this.offscreenTimer = 0;
  464. } else {
  465. this.offscreenTimer += deltaTime;
  466. if (this.offscreenTimer >= this.maxTimeOffScreen) {
  467. transform.position.set(0, 0, 0);
  468. }
  469. }
  470. }
  471. }
  472. function init() {
  473. // hide the loading bar
  474. const loadingElem = document.querySelector('#loading');
  475. loadingElem.style.display = 'none';
  476. prepModelsAndAnimations();
  477. {
  478. const gameObject = gameObjectManager.createGameObject(camera, 'camera');
  479. globals.cameraInfo = gameObject.addComponent(CameraInfo);
  480. }
  481. {
  482. const gameObject = gameObjectManager.createGameObject(scene, 'player');
  483. gameObject.addComponent(Player);
  484. }
  485. }
  486. function resizeRendererToDisplaySize(renderer) {
  487. const canvas = renderer.domElement;
  488. const width = canvas.clientWidth;
  489. const height = canvas.clientHeight;
  490. const needResize = canvas.width !== width || canvas.height !== height;
  491. if (needResize) {
  492. renderer.setSize(width, height, false);
  493. }
  494. return needResize;
  495. }
  496. let then = 0;
  497. function render(now) {
  498. // convert to seconds
  499. globals.time = now * 0.001;
  500. // make sure delta time isn't too big.
  501. globals.deltaTime = Math.min(globals.time - then, 1 / 20);
  502. then = globals.time;
  503. if (resizeRendererToDisplaySize(renderer)) {
  504. const canvas = renderer.domElement;
  505. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  506. camera.updateProjectionMatrix();
  507. }
  508. gameObjectManager.update();
  509. inputManager.update();
  510. renderer.render(scene, camera);
  511. requestAnimationFrame(render);
  512. }
  513. requestAnimationFrame(render);
  514. }
  515. main();
  516. </script>
  517. </html>