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

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