game-player-input.html 15 KB

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