threejs-game-conga-line.html 24 KB

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