threejs-game-conga-line.html 23 KB

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