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

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