game-conga-line.html 22 KB

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