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

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