game-player-input.html 15 KB

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