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

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