game-conga-line.html 22 KB

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