2
0

game-conga-line.html 23 KB

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