threejs-game-player-input.html 15 KB

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