game-conga-line.html 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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</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. #labels {
  106. position: absolute; /* let us position ourself inside the container */
  107. left: 0; /* make our position the top left of the container */
  108. top: 0;
  109. color: white;
  110. width: 100%;
  111. height: 100%;
  112. overflow: hidden;
  113. pointer-events: none;
  114. }
  115. #labels>div {
  116. position: absolute; /* let us position them inside the container */
  117. left: 0; /* make their default position the top left of the container */
  118. top: 0;
  119. font-size: large;
  120. font-family: monospace;
  121. user-select: none; /* don't let the text get selected */
  122. text-shadow: /* create a black outline */
  123. -1px -1px 0 #000,
  124. 0 -1px 0 #000,
  125. 1px -1px 0 #000,
  126. 1px 0 0 #000,
  127. 1px 1px 0 #000,
  128. 0 1px 0 #000,
  129. -1px 1px 0 #000,
  130. -1px 0 0 #000;
  131. }
  132. </style>
  133. </head>
  134. <body>
  135. <canvas id="c" tabindex="1"></canvas>
  136. <div id="ui">
  137. <div id="left"><img src="resources/images/left.svg"></div>
  138. <div style="flex: 0 0 40px;"></div>
  139. <div id="right"><img src="resources/images/right.svg"></div>
  140. </div>
  141. <div id="loading">
  142. <div>
  143. <div>...loading...</div>
  144. <div class="progress"><div id="progressbar"></div></div>
  145. </div>
  146. </div>
  147. <div id="labels"></div>
  148. </body>
  149. <!-- Import maps polyfill -->
  150. <!-- Remove this when import maps will be widely supported -->
  151. <script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
  152. <script type="importmap">
  153. {
  154. "imports": {
  155. "three": "../../build/three.module.js"
  156. }
  157. }
  158. </script>
  159. <script type="module">
  160. import * as THREE from 'three';
  161. import {OrbitControls} from '../../examples/jsm/controls/OrbitControls.js';
  162. import {GLTFLoader} from '../../examples/jsm/loaders/GLTFLoader.js';
  163. import * as SkeletonUtils from '../../examples/jsm/utils/SkeletonUtils.js';
  164. import {GUI} from '../../examples/jsm/libs/lil-gui.module.min.js';
  165. function main() {
  166. const canvas = document.querySelector('#c');
  167. const renderer = new THREE.WebGLRenderer({canvas});
  168. renderer.outputEncoding = THREE.sRGBEncoding;
  169. const fov = 45;
  170. const aspect = 2; // the canvas default
  171. const near = 0.1;
  172. const far = 1000;
  173. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  174. camera.position.set(0, 40, 80);
  175. const controls = new OrbitControls(camera, canvas);
  176. controls.target.set(0, 5, 0);
  177. controls.update();
  178. const scene = new THREE.Scene();
  179. scene.background = new THREE.Color('white');
  180. function addLight(...pos) {
  181. const color = 0xFFFFFF;
  182. const intensity = 0.8;
  183. const light = new THREE.DirectionalLight(color, intensity);
  184. light.position.set(...pos);
  185. scene.add(light);
  186. scene.add(light.target);
  187. }
  188. addLight(5, 5, 2);
  189. addLight(-5, 5, 5);
  190. const manager = new THREE.LoadingManager();
  191. manager.onLoad = init;
  192. const progressbarElem = document.querySelector('#progressbar');
  193. manager.onProgress = (url, itemsLoaded, itemsTotal) => {
  194. progressbarElem.style.width = `${itemsLoaded / itemsTotal * 100 | 0}%`;
  195. };
  196. const models = {
  197. pig: { url: 'resources/models/animals/Pig.gltf' },
  198. cow: { url: 'resources/models/animals/Cow.gltf' },
  199. llama: { url: 'resources/models/animals/Llama.gltf' },
  200. pug: { url: 'resources/models/animals/Pug.gltf' },
  201. sheep: { url: 'resources/models/animals/Sheep.gltf' },
  202. zebra: { url: 'resources/models/animals/Zebra.gltf' },
  203. horse: { url: 'resources/models/animals/Horse.gltf' },
  204. knight: { url: 'resources/models/knight/KnightCharacter.gltf' },
  205. };
  206. {
  207. const gltfLoader = new GLTFLoader(manager);
  208. for (const model of Object.values(models)) {
  209. gltfLoader.load(model.url, (gltf) => {
  210. model.gltf = gltf;
  211. });
  212. }
  213. }
  214. function prepModelsAndAnimations() {
  215. const box = new THREE.Box3();
  216. const size = new THREE.Vector3();
  217. Object.values(models).forEach(model => {
  218. box.setFromObject(model.gltf.scene);
  219. box.getSize(size);
  220. model.size = size.length();
  221. const animsByName = {};
  222. model.gltf.animations.forEach((clip) => {
  223. animsByName[clip.name] = clip;
  224. // Should really fix this in .blend file
  225. if (clip.name === 'Walk') {
  226. clip.duration /= 2;
  227. }
  228. });
  229. model.animations = animsByName;
  230. });
  231. }
  232. // Keeps the state of keys/buttons
  233. //
  234. // You can check
  235. //
  236. // inputManager.keys.left.down
  237. //
  238. // to see if the left key is currently held down
  239. // and you can check
  240. //
  241. // inputManager.keys.left.justPressed
  242. //
  243. // To see if the left key was pressed this frame
  244. //
  245. // Keys are 'left', 'right', 'a', 'b', 'up', 'down'
  246. class InputManager {
  247. constructor() {
  248. this.keys = {};
  249. const keyMap = new Map();
  250. const setKey = (keyName, pressed) => {
  251. const keyState = this.keys[keyName];
  252. keyState.justPressed = pressed && !keyState.down;
  253. keyState.down = pressed;
  254. };
  255. const addKey = (keyCode, name) => {
  256. this.keys[name] = { down: false, justPressed: false };
  257. keyMap.set(keyCode, name);
  258. };
  259. const setKeyFromKeyCode = (keyCode, pressed) => {
  260. const keyName = keyMap.get(keyCode);
  261. if (!keyName) {
  262. return;
  263. }
  264. setKey(keyName, pressed);
  265. };
  266. addKey(37, 'left');
  267. addKey(39, 'right');
  268. addKey(38, 'up');
  269. addKey(40, 'down');
  270. addKey(90, 'a');
  271. addKey(88, 'b');
  272. window.addEventListener('keydown', (e) => {
  273. setKeyFromKeyCode(e.keyCode, true);
  274. });
  275. window.addEventListener('keyup', (e) => {
  276. setKeyFromKeyCode(e.keyCode, false);
  277. });
  278. const sides = [
  279. { elem: document.querySelector('#left'), key: 'left' },
  280. { elem: document.querySelector('#right'), key: 'right' },
  281. ];
  282. // note: not a good design?
  283. // The last direction the user presses should take
  284. // precedence. Example: User presses L, without letting go of
  285. // L user presses R. Input should now be R. User lets off R
  286. // Input should now be L.
  287. // With this code if user pressed both L and R result is nothing
  288. const clearKeys = () => {
  289. for (const {key} of sides) {
  290. setKey(key, false);
  291. }
  292. };
  293. const handleMouseMove = (e) => {
  294. e.preventDefault();
  295. // this is needed because we call preventDefault();
  296. // we also gave the canvas a tabindex so it can
  297. // become the focus
  298. canvas.focus();
  299. window.addEventListener('pointermove', handleMouseMove);
  300. window.addEventListener('pointerup', handleMouseUp);
  301. for (const {elem, key} of sides) {
  302. let pressed = false;
  303. const rect = elem.getBoundingClientRect();
  304. const x = e.clientX;
  305. const y = e.clientY;
  306. const inRect = x >= rect.left && x < rect.right &&
  307. y >= rect.top && y < rect.bottom;
  308. if (inRect) {
  309. pressed = true;
  310. }
  311. setKey(key, pressed);
  312. }
  313. };
  314. function handleMouseUp() {
  315. clearKeys();
  316. window.removeEventListener('pointermove', handleMouseMove, {passive: false});
  317. window.removeEventListener('pointerup', handleMouseUp);
  318. }
  319. const uiElem = document.querySelector('#ui');
  320. uiElem.addEventListener('pointerdown', handleMouseMove, {passive: false});
  321. uiElem.addEventListener('touchstart', (e) => {
  322. // prevent scrolling
  323. e.preventDefault();
  324. }, {passive: false});
  325. }
  326. update() {
  327. for (const keyState of Object.values(this.keys)) {
  328. if (keyState.justPressed) {
  329. keyState.justPressed = false;
  330. }
  331. }
  332. }
  333. }
  334. function removeArrayElement(array, element) {
  335. const ndx = array.indexOf(element);
  336. if (ndx >= 0) {
  337. array.splice(ndx, 1);
  338. }
  339. }
  340. class SafeArray {
  341. constructor() {
  342. this.array = [];
  343. this.addQueue = [];
  344. this.removeQueue = new Set();
  345. }
  346. get isEmpty() {
  347. return this.addQueue.length + this.array.length > 0;
  348. }
  349. add(element) {
  350. this.addQueue.push(element);
  351. }
  352. remove(element) {
  353. this.removeQueue.add(element);
  354. }
  355. forEach(fn) {
  356. this._addQueued();
  357. this._removeQueued();
  358. for (const element of this.array) {
  359. if (this.removeQueue.has(element)) {
  360. continue;
  361. }
  362. fn(element);
  363. }
  364. this._removeQueued();
  365. }
  366. _addQueued() {
  367. if (this.addQueue.length) {
  368. this.array.splice(this.array.length, 0, ...this.addQueue);
  369. this.addQueue = [];
  370. }
  371. }
  372. _removeQueued() {
  373. if (this.removeQueue.size) {
  374. this.array = this.array.filter(element => !this.removeQueue.has(element));
  375. this.removeQueue.clear();
  376. }
  377. }
  378. }
  379. class GameObjectManager {
  380. constructor() {
  381. this.gameObjects = new SafeArray();
  382. }
  383. createGameObject(parent, name) {
  384. const gameObject = new GameObject(parent, name);
  385. this.gameObjects.add(gameObject);
  386. return gameObject;
  387. }
  388. removeGameObject(gameObject) {
  389. this.gameObjects.remove(gameObject);
  390. }
  391. update() {
  392. this.gameObjects.forEach(gameObject => gameObject.update());
  393. }
  394. }
  395. const kForward = new THREE.Vector3(0, 0, 1);
  396. const globals = {
  397. camera,
  398. canvas,
  399. debug: true,
  400. time: 0,
  401. moveSpeed: 16,
  402. deltaTime: 0,
  403. player: null,
  404. congaLine: [],
  405. };
  406. const gameObjectManager = new GameObjectManager();
  407. const inputManager = new InputManager();
  408. class GameObject {
  409. constructor(parent, name) {
  410. this.name = name;
  411. this.components = [];
  412. this.transform = new THREE.Object3D();
  413. parent.add(this.transform);
  414. }
  415. addComponent(ComponentType, ...args) {
  416. const component = new ComponentType(this, ...args);
  417. this.components.push(component);
  418. return component;
  419. }
  420. removeComponent(component) {
  421. removeArrayElement(this.components, component);
  422. }
  423. getComponent(ComponentType) {
  424. return this.components.find(c => c instanceof ComponentType);
  425. }
  426. update() {
  427. for (const component of this.components) {
  428. component.update();
  429. }
  430. }
  431. }
  432. // Base for all components
  433. class Component {
  434. constructor(gameObject) {
  435. this.gameObject = gameObject;
  436. }
  437. update() {
  438. }
  439. }
  440. class CameraInfo extends Component {
  441. constructor(gameObject) {
  442. super(gameObject);
  443. this.projScreenMatrix = new THREE.Matrix4();
  444. this.frustum = new THREE.Frustum();
  445. }
  446. update() {
  447. const {camera} = globals;
  448. this.projScreenMatrix.multiplyMatrices(
  449. camera.projectionMatrix,
  450. camera.matrixWorldInverse);
  451. this.frustum.setFromProjectionMatrix(this.projScreenMatrix);
  452. }
  453. }
  454. class SkinInstance extends Component {
  455. constructor(gameObject, model) {
  456. super(gameObject);
  457. this.model = model;
  458. this.animRoot = SkeletonUtils.clone(this.model.gltf.scene);
  459. this.mixer = new THREE.AnimationMixer(this.animRoot);
  460. gameObject.transform.add(this.animRoot);
  461. this.actions = {};
  462. }
  463. setAnimation(animName) {
  464. const clip = this.model.animations[animName];
  465. // turn off all current actions
  466. for (const action of Object.values(this.actions)) {
  467. action.enabled = false;
  468. }
  469. // get or create existing action for clip
  470. const action = this.mixer.clipAction(clip);
  471. action.enabled = true;
  472. action.reset();
  473. action.play();
  474. this.actions[animName] = action;
  475. }
  476. update() {
  477. this.mixer.update(globals.deltaTime);
  478. }
  479. }
  480. class FiniteStateMachine {
  481. constructor(states, initialState) {
  482. this.states = states;
  483. this.transition(initialState);
  484. }
  485. get state() {
  486. return this.currentState;
  487. }
  488. transition(state) {
  489. const oldState = this.states[this.currentState];
  490. if (oldState && oldState.exit) {
  491. oldState.exit.call(this);
  492. }
  493. this.currentState = state;
  494. const newState = this.states[state];
  495. if (newState.enter) {
  496. newState.enter.call(this);
  497. }
  498. }
  499. update() {
  500. const state = this.states[this.currentState];
  501. if (state.update) {
  502. state.update.call(this);
  503. }
  504. }
  505. }
  506. const gui = new GUI();
  507. gui.add(globals, 'debug').onChange(showHideDebugInfo);
  508. const labelContainerElem = document.querySelector('#labels');
  509. function showHideDebugInfo() {
  510. labelContainerElem.style.display = globals.debug ? '' : 'none';
  511. }
  512. class StateDisplayHelper extends Component {
  513. constructor(gameObject, size) {
  514. super(gameObject);
  515. this.elem = document.createElement('div');
  516. labelContainerElem.appendChild(this.elem);
  517. this.pos = new THREE.Vector3();
  518. this.helper = new THREE.PolarGridHelper(size / 2, 1, 1, 16);
  519. gameObject.transform.add(this.helper);
  520. }
  521. setState(s) {
  522. this.elem.textContent = s;
  523. }
  524. setColor(cssColor) {
  525. this.elem.style.color = cssColor;
  526. this.helper.material.color.set(cssColor);
  527. }
  528. update() {
  529. this.helper.visible = globals.debug;
  530. if (!globals.debug) {
  531. return;
  532. }
  533. const {pos} = this;
  534. const {transform} = this.gameObject;
  535. const {canvas} = globals;
  536. pos.copy(transform.position);
  537. // get the normalized screen coordinate of that position
  538. // x and y will be in the -1 to +1 range with x = -1 being
  539. // on the left and y = -1 being on the bottom
  540. pos.project(globals.camera);
  541. // convert the normalized position to CSS coordinates
  542. const x = (pos.x * .5 + .5) * canvas.clientWidth;
  543. const y = (pos.y * -.5 + .5) * canvas.clientHeight;
  544. // move the elem to that position
  545. this.elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  546. }
  547. }
  548. class Player extends Component {
  549. constructor(gameObject) {
  550. super(gameObject);
  551. const model = models.knight;
  552. globals.playerRadius = model.size / 2;
  553. this.text = gameObject.addComponent(StateDisplayHelper, model.size);
  554. this.skinInstance = gameObject.addComponent(SkinInstance, model);
  555. this.skinInstance.setAnimation('Run');
  556. this.turnSpeed = globals.moveSpeed / 4;
  557. this.offscreenTimer = 0;
  558. this.maxTimeOffScreen = 3;
  559. }
  560. update() {
  561. const {deltaTime, moveSpeed, cameraInfo} = globals;
  562. const {transform} = this.gameObject;
  563. const delta = (inputManager.keys.left.down ? 1 : 0) +
  564. (inputManager.keys.right.down ? -1 : 0);
  565. transform.rotation.y += this.turnSpeed * delta * deltaTime;
  566. transform.translateOnAxis(kForward, moveSpeed * deltaTime);
  567. const {frustum} = cameraInfo;
  568. if (frustum.containsPoint(transform.position)) {
  569. this.offscreenTimer = 0;
  570. } else {
  571. this.offscreenTimer += deltaTime;
  572. if (this.offscreenTimer >= this.maxTimeOffScreen) {
  573. transform.position.set(0, 0, 0);
  574. }
  575. }
  576. }
  577. }
  578. // Returns true of obj1 and obj2 are close
  579. function isClose(obj1, obj1Radius, obj2, obj2Radius) {
  580. const minDist = obj1Radius + obj2Radius;
  581. const dist = obj1.position.distanceTo(obj2.position);
  582. return dist < minDist;
  583. }
  584. // keeps v between -min and +min
  585. function minMagnitude(v, min) {
  586. return Math.abs(v) > min
  587. ? min * Math.sign(v)
  588. : v;
  589. }
  590. const aimTowardAndGetDistance = function() {
  591. const delta = new THREE.Vector3();
  592. return function aimTowardAndGetDistance(source, targetPos, maxTurn) {
  593. delta.subVectors(targetPos, source.position);
  594. // compute the direction we want to be facing
  595. const targetRot = Math.atan2(delta.x, delta.z) + Math.PI * 1.5;
  596. // rotate in the shortest direction
  597. const deltaRot = (targetRot - source.rotation.y + Math.PI * 1.5) % (Math.PI * 2) - Math.PI;
  598. // make sure we don't turn faster than maxTurn
  599. const deltaRotation = minMagnitude(deltaRot, maxTurn);
  600. // keep rotation between 0 and Math.PI * 2
  601. source.rotation.y = THREE.MathUtils.euclideanModulo(
  602. source.rotation.y + deltaRotation, Math.PI * 2);
  603. // return the distance to the target
  604. return delta.length();
  605. };
  606. }();
  607. class Animal extends Component {
  608. constructor(gameObject, model) {
  609. super(gameObject);
  610. this.helper = gameObject.addComponent(StateDisplayHelper, model.size);
  611. const hitRadius = model.size / 2;
  612. const skinInstance = gameObject.addComponent(SkinInstance, model);
  613. skinInstance.mixer.timeScale = globals.moveSpeed / 4;
  614. const transform = gameObject.transform;
  615. const playerTransform = globals.player.gameObject.transform;
  616. const maxTurnSpeed = Math.PI * (globals.moveSpeed / 4);
  617. const targetHistory = [];
  618. let targetNdx = 0;
  619. function addHistory() {
  620. const targetGO = globals.congaLine[targetNdx];
  621. const newTargetPos = new THREE.Vector3();
  622. newTargetPos.copy(targetGO.transform.position);
  623. targetHistory.push(newTargetPos);
  624. }
  625. this.fsm = new FiniteStateMachine({
  626. idle: {
  627. enter: () => {
  628. skinInstance.setAnimation('Idle');
  629. },
  630. update: () => {
  631. // check if player is near
  632. if (isClose(transform, hitRadius, playerTransform, globals.playerRadius)) {
  633. this.fsm.transition('waitForEnd');
  634. }
  635. },
  636. },
  637. waitForEnd: {
  638. enter: () => {
  639. skinInstance.setAnimation('Jump');
  640. },
  641. update: () => {
  642. // get the gameObject at the end of the conga line
  643. const lastGO = globals.congaLine[globals.congaLine.length - 1];
  644. const deltaTurnSpeed = maxTurnSpeed * globals.deltaTime;
  645. const targetPos = lastGO.transform.position;
  646. aimTowardAndGetDistance(transform, targetPos, deltaTurnSpeed);
  647. // check if last thing in conga line is near
  648. if (isClose(transform, hitRadius, lastGO.transform, globals.playerRadius)) {
  649. this.fsm.transition('goToLast');
  650. }
  651. },
  652. },
  653. goToLast: {
  654. enter: () => {
  655. // remember who we're following
  656. targetNdx = globals.congaLine.length - 1;
  657. // add ourselves to the conga line
  658. globals.congaLine.push(gameObject);
  659. skinInstance.setAnimation('Walk');
  660. },
  661. update: () => {
  662. addHistory();
  663. // walk to the oldest point in the history
  664. const targetPos = targetHistory[0];
  665. const maxVelocity = globals.moveSpeed * globals.deltaTime;
  666. const deltaTurnSpeed = maxTurnSpeed * globals.deltaTime;
  667. const distance = aimTowardAndGetDistance(transform, targetPos, deltaTurnSpeed);
  668. const velocity = distance;
  669. transform.translateOnAxis(kForward, Math.min(velocity, maxVelocity));
  670. if (distance <= maxVelocity) {
  671. this.fsm.transition('follow');
  672. }
  673. },
  674. },
  675. follow: {
  676. update: () => {
  677. addHistory();
  678. // remove the oldest history and just put ourselves there.
  679. const targetPos = targetHistory.shift();
  680. transform.position.copy(targetPos);
  681. const deltaTurnSpeed = maxTurnSpeed * globals.deltaTime;
  682. aimTowardAndGetDistance(transform, targetHistory[0], deltaTurnSpeed);
  683. },
  684. },
  685. }, 'idle');
  686. }
  687. update() {
  688. this.fsm.update();
  689. const dir = THREE.MathUtils.radToDeg(this.gameObject.transform.rotation.y);
  690. this.helper.setState(`${this.fsm.state}:${dir.toFixed(0)}`);
  691. }
  692. }
  693. function init() {
  694. // hide the loading bar
  695. const loadingElem = document.querySelector('#loading');
  696. loadingElem.style.display = 'none';
  697. prepModelsAndAnimations();
  698. {
  699. const gameObject = gameObjectManager.createGameObject(camera, 'camera');
  700. globals.cameraInfo = gameObject.addComponent(CameraInfo);
  701. }
  702. {
  703. const gameObject = gameObjectManager.createGameObject(scene, 'player');
  704. globals.player = gameObject.addComponent(Player);
  705. globals.congaLine = [gameObject];
  706. }
  707. const animalModelNames = [
  708. 'pig',
  709. 'cow',
  710. 'llama',
  711. 'pug',
  712. 'sheep',
  713. 'zebra',
  714. 'horse',
  715. ];
  716. animalModelNames.forEach((name, ndx) => {
  717. const gameObject = gameObjectManager.createGameObject(scene, name);
  718. gameObject.addComponent(Animal, models[name]);
  719. gameObject.transform.position.x = (ndx + 1) * 5;
  720. });
  721. }
  722. function resizeRendererToDisplaySize(renderer) {
  723. const canvas = renderer.domElement;
  724. const width = canvas.clientWidth;
  725. const height = canvas.clientHeight;
  726. const needResize = canvas.width !== width || canvas.height !== height;
  727. if (needResize) {
  728. renderer.setSize(width, height, false);
  729. }
  730. return needResize;
  731. }
  732. let then = 0;
  733. function render(now) {
  734. // convert to seconds
  735. globals.time = now * 0.001;
  736. // make sure delta time isn't too big.
  737. globals.deltaTime = Math.min(globals.time - then, 1 / 20);
  738. then = globals.time;
  739. if (resizeRendererToDisplaySize(renderer)) {
  740. const canvas = renderer.domElement;
  741. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  742. camera.updateProjectionMatrix();
  743. }
  744. gameObjectManager.update();
  745. inputManager.update();
  746. renderer.render(scene, camera);
  747. requestAnimationFrame(render);
  748. }
  749. requestAnimationFrame(render);
  750. }
  751. main();
  752. </script>
  753. </html>