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

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