threejs-game-player-input.html 15 KB

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