game-conga-line-w-notes.html 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  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=no">
  7. <title>Three.js - Game w/notes</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.useLegacyLights = false;
  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 = 2.5;
  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* waitFrames(numFrames) {
  336. // while (numFrames > 0) {
  337. // --numFrames;
  338. // yield;
  339. // }
  340. // }
  341. function* waitSeconds( duration ) {
  342. while ( duration > 0 ) {
  343. duration -= globals.deltaTime;
  344. yield;
  345. }
  346. }
  347. class CoroutineRunner {
  348. constructor() {
  349. this.generatorStacks = [];
  350. this.addQueue = [];
  351. this.removeQueue = new Set();
  352. }
  353. isBusy() {
  354. return this.addQueue.length + this.generatorStacks.length > 0;
  355. }
  356. add( generator, delay = 0 ) {
  357. const genStack = [ generator ];
  358. if ( delay ) {
  359. genStack.push( waitSeconds( delay ) );
  360. }
  361. this.addQueue.push( genStack );
  362. }
  363. remove( generator ) {
  364. this.removeQueue.add( generator );
  365. }
  366. update() {
  367. this._addQueued();
  368. this._removeQueued();
  369. for ( const genStack of this.generatorStacks ) {
  370. const main = genStack[ 0 ];
  371. // Handle if one coroutine removes another
  372. if ( this.removeQueue.has( main ) ) {
  373. continue;
  374. }
  375. while ( genStack.length ) {
  376. const topGen = genStack[ genStack.length - 1 ];
  377. const { value, done } = topGen.next();
  378. if ( done ) {
  379. if ( genStack.length === 1 ) {
  380. this.removeQueue.add( topGen );
  381. break;
  382. }
  383. genStack.pop();
  384. } else if ( value ) {
  385. genStack.push( value );
  386. } else {
  387. break;
  388. }
  389. }
  390. }
  391. this._removeQueued();
  392. }
  393. _addQueued() {
  394. if ( this.addQueue.length ) {
  395. this.generatorStacks.splice( this.generatorStacks.length, 0, ...this.addQueue );
  396. this.addQueue = [];
  397. }
  398. }
  399. _removeQueued() {
  400. if ( this.removeQueue.size ) {
  401. this.generatorStacks = this.generatorStacks.filter( genStack => ! this.removeQueue.has( genStack[ 0 ] ) );
  402. this.removeQueue.clear();
  403. }
  404. }
  405. }
  406. function removeArrayElement( array, element ) {
  407. const ndx = array.indexOf( element );
  408. if ( ndx >= 0 ) {
  409. array.splice( ndx, 1 );
  410. }
  411. }
  412. class SafeArray {
  413. constructor() {
  414. this.array = [];
  415. this.addQueue = [];
  416. this.removeQueue = new Set();
  417. }
  418. get isEmpty() {
  419. return this.addQueue.length + this.array.length > 0;
  420. }
  421. add( element ) {
  422. this.addQueue.push( element );
  423. }
  424. remove( element ) {
  425. this.removeQueue.add( element );
  426. }
  427. forEach( fn ) {
  428. this._addQueued();
  429. this._removeQueued();
  430. for ( const element of this.array ) {
  431. if ( this.removeQueue.has( element ) ) {
  432. continue;
  433. }
  434. fn( element );
  435. }
  436. this._removeQueued();
  437. }
  438. _addQueued() {
  439. if ( this.addQueue.length ) {
  440. this.array.splice( this.array.length, 0, ...this.addQueue );
  441. this.addQueue = [];
  442. }
  443. }
  444. _removeQueued() {
  445. if ( this.removeQueue.size ) {
  446. this.array = this.array.filter( element => ! this.removeQueue.has( element ) );
  447. this.removeQueue.clear();
  448. }
  449. }
  450. }
  451. class GameObjectManager {
  452. constructor() {
  453. this.gameObjects = new SafeArray();
  454. }
  455. createGameObject( parent, name ) {
  456. const gameObject = new GameObject( parent, name );
  457. this.gameObjects.add( gameObject );
  458. return gameObject;
  459. }
  460. removeGameObject( gameObject ) {
  461. this.gameObjects.remove( gameObject );
  462. }
  463. update() {
  464. this.gameObjects.forEach( gameObject => gameObject.update() );
  465. }
  466. }
  467. const kForward = new THREE.Vector3( 0, 0, 1 );
  468. const globals = {
  469. camera,
  470. canvas,
  471. debug: false,
  472. time: 0,
  473. moveSpeed: 16,
  474. deltaTime: 0,
  475. player: null,
  476. congaLine: [],
  477. };
  478. const gameObjectManager = new GameObjectManager();
  479. const inputManager = new InputManager();
  480. class GameObject {
  481. constructor( parent, name ) {
  482. this.name = name;
  483. this.components = [];
  484. this.transform = new THREE.Object3D();
  485. this.transform.name = name;
  486. parent.add( this.transform );
  487. }
  488. addComponent( ComponentType, ...args ) {
  489. const component = new ComponentType( this, ...args );
  490. this.components.push( component );
  491. return component;
  492. }
  493. removeComponent( component ) {
  494. removeArrayElement( this.components, component );
  495. }
  496. getComponent( ComponentType ) {
  497. return this.components.find( c => c instanceof ComponentType );
  498. }
  499. update() {
  500. for ( const component of this.components ) {
  501. component.update();
  502. }
  503. }
  504. }
  505. // Base for all components
  506. class Component {
  507. constructor( gameObject ) {
  508. this.gameObject = gameObject;
  509. }
  510. update() {
  511. }
  512. }
  513. class CameraInfo extends Component {
  514. constructor( gameObject ) {
  515. super( gameObject );
  516. this.projScreenMatrix = new THREE.Matrix4();
  517. this.frustum = new THREE.Frustum();
  518. }
  519. update() {
  520. const { camera } = globals;
  521. this.projScreenMatrix.multiplyMatrices(
  522. camera.projectionMatrix,
  523. camera.matrixWorldInverse );
  524. this.frustum.setFromProjectionMatrix( this.projScreenMatrix );
  525. }
  526. }
  527. class SkinInstance extends Component {
  528. constructor( gameObject, model ) {
  529. super( gameObject );
  530. this.model = model;
  531. this.animRoot = SkeletonUtils.clone( this.model.gltf.scene );
  532. this.mixer = new THREE.AnimationMixer( this.animRoot );
  533. gameObject.transform.add( this.animRoot );
  534. this.actions = {};
  535. }
  536. setAnimation( animName ) {
  537. const clip = this.model.animations[ animName ];
  538. // turn off all current actions
  539. for ( const action of Object.values( this.actions ) ) {
  540. action.enabled = false;
  541. }
  542. // get or create existing action for clip
  543. const action = this.mixer.clipAction( clip );
  544. action.enabled = true;
  545. action.reset();
  546. action.play();
  547. this.actions[ animName ] = action;
  548. }
  549. update() {
  550. this.mixer.update( globals.deltaTime );
  551. }
  552. }
  553. class FiniteStateMachine {
  554. constructor( states, initialState ) {
  555. this.states = states;
  556. this.transition( initialState );
  557. }
  558. get state() {
  559. return this.currentState;
  560. }
  561. transition( state ) {
  562. const oldState = this.states[ this.currentState ];
  563. if ( oldState && oldState.exit ) {
  564. oldState.exit.call( this );
  565. }
  566. this.currentState = state;
  567. const newState = this.states[ state ];
  568. if ( newState.enter ) {
  569. newState.enter.call( this );
  570. }
  571. }
  572. update() {
  573. const state = this.states[ this.currentState ];
  574. if ( state.update ) {
  575. state.update.call( this );
  576. }
  577. }
  578. }
  579. const gui = new GUI();
  580. gui.add( globals, 'debug' ).onChange( showHideDebugInfo );
  581. gui.close();
  582. const labelContainerElem = document.querySelector( '#labels' );
  583. function showHideDebugInfo() {
  584. labelContainerElem.style.display = globals.debug ? '' : 'none';
  585. }
  586. showHideDebugInfo();
  587. class StateDisplayHelper extends Component {
  588. constructor( gameObject, size ) {
  589. super( gameObject );
  590. this.elem = document.createElement( 'div' );
  591. labelContainerElem.appendChild( this.elem );
  592. this.pos = new THREE.Vector3();
  593. this.helper = new THREE.PolarGridHelper( size / 2, 1, 1, 16 );
  594. gameObject.transform.add( this.helper );
  595. }
  596. setState( s ) {
  597. this.elem.textContent = s;
  598. }
  599. setColor( cssColor ) {
  600. this.elem.style.color = cssColor;
  601. this.helper.material.color.set( cssColor );
  602. }
  603. update() {
  604. this.helper.visible = globals.debug;
  605. if ( ! globals.debug ) {
  606. return;
  607. }
  608. const { pos } = this;
  609. const { transform } = this.gameObject;
  610. const { canvas } = globals;
  611. pos.copy( transform.position );
  612. // get the normalized screen coordinate of that position
  613. // x and y will be in the -1 to +1 range with x = -1 being
  614. // on the left and y = -1 being on the bottom
  615. pos.project( globals.camera );
  616. // convert the normalized position to CSS coordinates
  617. const x = ( pos.x * .5 + .5 ) * canvas.clientWidth;
  618. const y = ( pos.y * - .5 + .5 ) * canvas.clientHeight;
  619. // move the elem to that position
  620. this.elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
  621. }
  622. }
  623. function rand( min, max ) {
  624. if ( max === undefined ) {
  625. max = min;
  626. min = 0;
  627. }
  628. return Math.random() * ( max - min ) + min;
  629. }
  630. function makeTextTexture( str ) {
  631. const ctx = document.createElement( 'canvas' ).getContext( '2d' );
  632. ctx.canvas.width = 64;
  633. ctx.canvas.height = 64;
  634. ctx.font = '60px sans-serif';
  635. ctx.textAlign = 'center';
  636. ctx.textBaseline = 'middle';
  637. ctx.fillStyle = '#FFF';
  638. ctx.fillText( str, ctx.canvas.width / 2, ctx.canvas.height / 2 );
  639. return new THREE.CanvasTexture( ctx.canvas );
  640. }
  641. const noteTexture = makeTextTexture( '♪' );
  642. class Note extends Component {
  643. constructor( gameObject ) {
  644. super( gameObject );
  645. const { transform } = gameObject;
  646. const noteMaterial = new THREE.SpriteMaterial( {
  647. color: new THREE.Color().setHSL( rand( 1 ), 1, 0.5 ),
  648. map: noteTexture,
  649. side: THREE.DoubleSide,
  650. transparent: true,
  651. } );
  652. const note = new THREE.Sprite( noteMaterial );
  653. note.scale.setScalar( 3 );
  654. transform.add( note );
  655. this.runner = new CoroutineRunner();
  656. const direction = new THREE.Vector3( rand( - 0.2, 0.2 ), 1, rand( - 0.2, 0.2 ) );
  657. function* moveAndRemove() {
  658. for ( let i = 0; i < 60; ++ i ) {
  659. transform.translateOnAxis( direction, globals.deltaTime * 10 );
  660. noteMaterial.opacity = 1 - ( i / 60 );
  661. yield;
  662. }
  663. transform.parent.remove( transform );
  664. gameObjectManager.removeGameObject( gameObject );
  665. }
  666. this.runner.add( moveAndRemove() );
  667. }
  668. update() {
  669. this.runner.update();
  670. }
  671. }
  672. class Player extends Component {
  673. constructor( gameObject ) {
  674. super( gameObject );
  675. const model = models.knight;
  676. globals.playerRadius = model.size / 2;
  677. this.text = gameObject.addComponent( StateDisplayHelper, model.size );
  678. this.skinInstance = gameObject.addComponent( SkinInstance, model );
  679. this.skinInstance.setAnimation( 'Run' );
  680. this.turnSpeed = globals.moveSpeed / 4;
  681. this.offscreenTimer = 0;
  682. this.maxTimeOffScreen = 3;
  683. this.runner = new CoroutineRunner();
  684. function* emitNotes() {
  685. for ( ;; ) {
  686. yield waitSeconds( rand( 0.5, 1 ) );
  687. const noteGO = gameObjectManager.createGameObject( scene, 'note' );
  688. noteGO.transform.position.copy( gameObject.transform.position );
  689. noteGO.transform.position.y += 5;
  690. noteGO.addComponent( Note );
  691. }
  692. }
  693. this.runner.add( emitNotes() );
  694. }
  695. update() {
  696. this.runner.update();
  697. const { deltaTime, moveSpeed, cameraInfo } = globals;
  698. const { transform } = this.gameObject;
  699. const delta = ( inputManager.keys.left.down ? 1 : 0 ) +
  700. ( inputManager.keys.right.down ? - 1 : 0 );
  701. transform.rotation.y += this.turnSpeed * delta * deltaTime;
  702. transform.translateOnAxis( kForward, moveSpeed * deltaTime );
  703. const { frustum } = cameraInfo;
  704. if ( frustum.containsPoint( transform.position ) ) {
  705. this.offscreenTimer = 0;
  706. } else {
  707. this.offscreenTimer += deltaTime;
  708. if ( this.offscreenTimer >= this.maxTimeOffScreen ) {
  709. transform.position.set( 0, 0, 0 );
  710. }
  711. }
  712. }
  713. }
  714. // Returns true of obj1 and obj2 are close
  715. function isClose( obj1, obj1Radius, obj2, obj2Radius ) {
  716. const minDist = obj1Radius + obj2Radius;
  717. const dist = obj1.position.distanceTo( obj2.position );
  718. return dist < minDist;
  719. }
  720. // keeps v between -min and +min
  721. function minMagnitude( v, min ) {
  722. return Math.abs( v ) > min
  723. ? min * Math.sign( v )
  724. : v;
  725. }
  726. const aimTowardAndGetDistance = function () {
  727. const delta = new THREE.Vector3();
  728. return function aimTowardAndGetDistance( source, targetPos, maxTurn ) {
  729. delta.subVectors( targetPos, source.position );
  730. // compute the direction we want to be facing
  731. const targetRot = Math.atan2( delta.x, delta.z ) + Math.PI * 1.5;
  732. // rotate in the shortest direction
  733. const deltaRot = ( targetRot - source.rotation.y + Math.PI * 1.5 ) % ( Math.PI * 2 ) - Math.PI;
  734. // make sure we don't turn faster than maxTurn
  735. const deltaRotation = minMagnitude( deltaRot, maxTurn );
  736. // keep rotation between 0 and Math.PI * 2
  737. source.rotation.y = THREE.MathUtils.euclideanModulo(
  738. source.rotation.y + deltaRotation, Math.PI * 2 );
  739. // return the distance to the target
  740. return delta.length();
  741. };
  742. }();
  743. class Animal extends Component {
  744. constructor( gameObject, model ) {
  745. super( gameObject );
  746. this.helper = gameObject.addComponent( StateDisplayHelper, model.size );
  747. const hitRadius = model.size / 2;
  748. const skinInstance = gameObject.addComponent( SkinInstance, model );
  749. skinInstance.mixer.timeScale = globals.moveSpeed / 4;
  750. const transform = gameObject.transform;
  751. const playerTransform = globals.player.gameObject.transform;
  752. const maxTurnSpeed = Math.PI * ( globals.moveSpeed / 4 );
  753. const targetHistory = [];
  754. let targetNdx = 0;
  755. function addHistory() {
  756. const targetGO = globals.congaLine[ targetNdx ];
  757. const newTargetPos = new THREE.Vector3();
  758. newTargetPos.copy( targetGO.transform.position );
  759. targetHistory.push( newTargetPos );
  760. }
  761. this.fsm = new FiniteStateMachine( {
  762. idle: {
  763. enter: () => {
  764. skinInstance.setAnimation( 'Idle' );
  765. },
  766. update: () => {
  767. // check if player is near
  768. if ( isClose( transform, hitRadius, playerTransform, globals.playerRadius ) ) {
  769. this.fsm.transition( 'waitForEnd' );
  770. }
  771. },
  772. },
  773. waitForEnd: {
  774. enter: () => {
  775. skinInstance.setAnimation( 'Jump' );
  776. },
  777. update: () => {
  778. // get the gameObject at the end of the conga line
  779. const lastGO = globals.congaLine[ globals.congaLine.length - 1 ];
  780. const deltaTurnSpeed = maxTurnSpeed * globals.deltaTime;
  781. const targetPos = lastGO.transform.position;
  782. aimTowardAndGetDistance( transform, targetPos, deltaTurnSpeed );
  783. // check if last thing in conga line is near
  784. if ( isClose( transform, hitRadius, lastGO.transform, globals.playerRadius ) ) {
  785. this.fsm.transition( 'goToLast' );
  786. }
  787. },
  788. },
  789. goToLast: {
  790. enter: () => {
  791. // remember who we're following
  792. targetNdx = globals.congaLine.length - 1;
  793. // add ourselves to the conga line
  794. globals.congaLine.push( gameObject );
  795. skinInstance.setAnimation( 'Walk' );
  796. },
  797. update: () => {
  798. addHistory();
  799. // walk to the oldest point in the history
  800. const targetPos = targetHistory[ 0 ];
  801. const maxVelocity = globals.moveSpeed * globals.deltaTime;
  802. const deltaTurnSpeed = maxTurnSpeed * globals.deltaTime;
  803. const distance = aimTowardAndGetDistance( transform, targetPos, deltaTurnSpeed );
  804. const velocity = distance;
  805. transform.translateOnAxis( kForward, Math.min( velocity, maxVelocity ) );
  806. if ( distance <= maxVelocity ) {
  807. this.fsm.transition( 'follow' );
  808. }
  809. },
  810. },
  811. follow: {
  812. update: () => {
  813. addHistory();
  814. // remove the oldest history and just put ourselves there.
  815. const targetPos = targetHistory.shift();
  816. transform.position.copy( targetPos );
  817. const deltaTurnSpeed = maxTurnSpeed * globals.deltaTime;
  818. aimTowardAndGetDistance( transform, targetHistory[ 0 ], deltaTurnSpeed );
  819. },
  820. },
  821. }, 'idle' );
  822. }
  823. update() {
  824. this.fsm.update();
  825. const dir = THREE.MathUtils.radToDeg( this.gameObject.transform.rotation.y );
  826. this.helper.setState( `${this.fsm.state}:${dir.toFixed( 0 )}` );
  827. }
  828. }
  829. function init() {
  830. // hide the loading bar
  831. const loadingElem = document.querySelector( '#loading' );
  832. loadingElem.style.display = 'none';
  833. prepModelsAndAnimations();
  834. {
  835. const gameObject = gameObjectManager.createGameObject( camera, 'camera' );
  836. globals.cameraInfo = gameObject.addComponent( CameraInfo );
  837. }
  838. {
  839. const gameObject = gameObjectManager.createGameObject( scene, 'player' );
  840. globals.player = gameObject.addComponent( Player );
  841. globals.congaLine = [ gameObject ];
  842. }
  843. const animalModelNames = [
  844. 'pig',
  845. 'cow',
  846. 'llama',
  847. 'pug',
  848. 'sheep',
  849. 'zebra',
  850. 'horse',
  851. ];
  852. const base = new THREE.Object3D();
  853. const offset = new THREE.Object3D();
  854. base.add( offset );
  855. // position animals in a spiral.
  856. const numAnimals = 28;
  857. const arc = 10;
  858. const b = 10 / ( 2 * Math.PI );
  859. let r = 10;
  860. let phi = r / b;
  861. for ( let i = 0; i < numAnimals; ++ i ) {
  862. const name = animalModelNames[ rand( animalModelNames.length ) | 0 ];
  863. const gameObject = gameObjectManager.createGameObject( scene, name );
  864. gameObject.addComponent( Animal, models[ name ] );
  865. base.rotation.y = phi;
  866. offset.position.x = r;
  867. offset.updateWorldMatrix( true, false );
  868. offset.getWorldPosition( gameObject.transform.position );
  869. phi += arc / r;
  870. r = b * phi;
  871. }
  872. }
  873. function resizeRendererToDisplaySize( renderer ) {
  874. const canvas = renderer.domElement;
  875. const width = canvas.clientWidth;
  876. const height = canvas.clientHeight;
  877. const needResize = canvas.width !== width || canvas.height !== height;
  878. if ( needResize ) {
  879. renderer.setSize( width, height, false );
  880. }
  881. return needResize;
  882. }
  883. let then = 0;
  884. function render( now ) {
  885. // convert to seconds
  886. globals.time = now * 0.001;
  887. // make sure delta time isn't too big.
  888. globals.deltaTime = Math.min( globals.time - then, 1 / 20 );
  889. then = globals.time;
  890. if ( resizeRendererToDisplaySize( renderer ) ) {
  891. const canvas = renderer.domElement;
  892. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  893. camera.updateProjectionMatrix();
  894. }
  895. gameObjectManager.update();
  896. inputManager.update();
  897. renderer.render( scene, camera );
  898. requestAnimationFrame( render );
  899. }
  900. requestAnimationFrame( render );
  901. }
  902. main();
  903. </script>
  904. </html>