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

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