game-player-input.html 15 KB

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