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

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