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

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