threejs-game-just-player.html 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 - Just Player</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. #loading {
  25. position: absolute;
  26. left: 0;
  27. top: 0;
  28. width: 100%;
  29. height: 100%;
  30. display: flex;
  31. align-items: center;
  32. justify-content: center;
  33. text-align: center;
  34. font-size: xx-large;
  35. font-family: sans-serif;
  36. }
  37. #loading>div>div {
  38. padding: 2px;
  39. }
  40. .progress {
  41. width: 50vw;
  42. border: 1px solid black;
  43. }
  44. #progressbar {
  45. width: 0%;
  46. height: 1em;
  47. background-color: #888;
  48. background-image: linear-gradient(
  49. -45deg,
  50. rgba(255, 255, 255, .5) 25%,
  51. transparent 25%,
  52. transparent 50%,
  53. rgba(255, 255, 255, .5) 50%,
  54. rgba(255, 255, 255, .5) 75%,
  55. transparent 75%,
  56. transparent
  57. );
  58. background-size: 50px 50px;
  59. animation: progressanim 2s linear infinite;
  60. }
  61. @keyframes progressanim {
  62. 0% {
  63. background-position: 50px 50px;
  64. }
  65. 100% {
  66. background-position: 0 0;
  67. }
  68. }
  69. </style>
  70. </head>
  71. <body>
  72. <canvas id="c"></canvas>
  73. <div id="loading">
  74. <div>
  75. <div>...loading...</div>
  76. <div class="progress"><div id="progressbar"></div></div>
  77. </div>
  78. </div>
  79. </body>
  80. <script src="resources/threejs/r105/three.min.js"></script>
  81. <script src="resources/threejs/r105/js/controls/OrbitControls.js"></script>
  82. <script src="resources/threejs/r105/js/loaders/GLTFLoader.js"></script>
  83. <script src="resources/threejs/r105/js/utils/SkeletonUtils.js"></script>
  84. <script>
  85. 'use strict';
  86. /* global THREE */
  87. function main() {
  88. const canvas = document.querySelector('#c');
  89. const renderer = new THREE.WebGLRenderer({canvas});
  90. const fov = 45;
  91. const aspect = 2; // the canvas default
  92. const near = 0.1;
  93. const far = 1000;
  94. const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  95. camera.position.set(0, 40, 80);
  96. const controls = new THREE.OrbitControls(camera, canvas);
  97. controls.enableKeys = false;
  98. controls.target.set(0, 5, 0);
  99. controls.update();
  100. const scene = new THREE.Scene();
  101. scene.background = new THREE.Color('white');
  102. function addLight(...pos) {
  103. const color = 0xFFFFFF;
  104. const intensity = 1;
  105. const light = new THREE.DirectionalLight(color, intensity);
  106. light.position.set(...pos);
  107. scene.add(light);
  108. scene.add(light.target);
  109. }
  110. addLight(5, 5, 2);
  111. addLight(-5, 5, 5);
  112. const manager = new THREE.LoadingManager();
  113. manager.onLoad = init;
  114. const progressbarElem = document.querySelector('#progressbar');
  115. manager.onProgress = (url, itemsLoaded, itemsTotal) => {
  116. progressbarElem.style.width = `${itemsLoaded / itemsTotal * 100 | 0}%`;
  117. };
  118. const models = {
  119. pig: { url: 'resources/models/animals/Pig.gltf' },
  120. cow: { url: 'resources/models/animals/Cow.gltf' },
  121. llama: { url: 'resources/models/animals/Llama.gltf' },
  122. pug: { url: 'resources/models/animals/Pug.gltf' },
  123. sheep: { url: 'resources/models/animals/Sheep.gltf' },
  124. zebra: { url: 'resources/models/animals/Zebra.gltf' },
  125. horse: { url: 'resources/models/animals/Horse.gltf' },
  126. knight: { url: 'resources/models/knight/KnightCharacter.gltf' },
  127. };
  128. {
  129. const gltfLoader = new THREE.GLTFLoader(manager);
  130. for (const model of Object.values(models)) {
  131. gltfLoader.load(model.url, (gltf) => {
  132. model.gltf = gltf;
  133. });
  134. }
  135. }
  136. function prepModelsAndAnimations() {
  137. Object.values(models).forEach(model => {
  138. const animsByName = {};
  139. model.gltf.animations.forEach((clip) => {
  140. animsByName[clip.name] = clip;
  141. // Should really fix this in .blend file
  142. if (clip.name === 'Walk') {
  143. clip.duration /= 2;
  144. }
  145. });
  146. model.animations = animsByName;
  147. });
  148. }
  149. function removeArrayElement(array, element) {
  150. const ndx = array.indexOf(element);
  151. if (ndx >= 0) {
  152. array.splice(ndx, 1);
  153. }
  154. }
  155. class SafeArray {
  156. constructor() {
  157. this.array = [];
  158. this.addQueue = [];
  159. this.removeQueue = new Set();
  160. }
  161. get isEmpty() {
  162. return this.addQueue.length + this.array.length > 0;
  163. }
  164. add(element) {
  165. this.addQueue.push(element);
  166. }
  167. remove(element) {
  168. this.removeQueue.add(element);
  169. }
  170. forEach(fn) {
  171. this._addQueued();
  172. this._removeQueued();
  173. for (const element of this.array) {
  174. if (this.removeQueue.has(element)) {
  175. continue;
  176. }
  177. fn(element);
  178. }
  179. this._removeQueued();
  180. }
  181. _addQueued() {
  182. if (this.addQueue.length) {
  183. this.array.splice(this.array.length, 0, ...this.addQueue);
  184. this.addQueue = [];
  185. }
  186. }
  187. _removeQueued() {
  188. if (this.removeQueue.size) {
  189. this.array = this.array.filter(element => !this.removeQueue.has(element));
  190. this.removeQueue.clear();
  191. }
  192. }
  193. }
  194. class GameObjectManager {
  195. constructor() {
  196. this.gameObjects = new SafeArray();
  197. }
  198. createGameObject(parent, name) {
  199. const gameObject = new GameObject(parent, name);
  200. this.gameObjects.add(gameObject);
  201. return gameObject;
  202. }
  203. removeGameObject(gameObject) {
  204. this.gameObjects.remove(gameObject);
  205. }
  206. update() {
  207. this.gameObjects.forEach(gameObject => gameObject.update());
  208. }
  209. }
  210. const globals = {
  211. time: 0,
  212. deltaTime: 0,
  213. };
  214. const gameObjectManager = new GameObjectManager();
  215. class GameObject {
  216. constructor(parent, name) {
  217. this.name = name;
  218. this.components = [];
  219. this.transform = new THREE.Object3D();
  220. parent.add(this.transform);
  221. }
  222. addComponent(ComponentType, ...args) {
  223. const component = new ComponentType(this, ...args);
  224. this.components.push(component);
  225. return component;
  226. }
  227. removeComponent(component) {
  228. removeArrayElement(this.components, component);
  229. }
  230. getComponent(ComponentType) {
  231. return this.components.find(c => c instanceof ComponentType);
  232. }
  233. update() {
  234. for (const component of this.components) {
  235. component.update();
  236. }
  237. }
  238. }
  239. // Base for all components
  240. class Component {
  241. constructor(gameObject) {
  242. this.gameObject = gameObject;
  243. }
  244. update() {
  245. }
  246. }
  247. class SkinInstance extends Component {
  248. constructor(gameObject, model) {
  249. super(gameObject);
  250. this.model = model;
  251. this.animRoot = THREE.SkeletonUtils.clone(this.model.gltf.scene);
  252. this.mixer = new THREE.AnimationMixer(this.animRoot);
  253. gameObject.transform.add(this.animRoot);
  254. this.actions = {};
  255. }
  256. setAnimation(animName) {
  257. const clip = this.model.animations[animName];
  258. // turn off all current actions
  259. for (const action of Object.values(this.actions)) {
  260. action.enabled = false;
  261. }
  262. // get or create existing action for clip
  263. const action = this.mixer.clipAction(clip);
  264. action.enabled = true;
  265. action.reset();
  266. action.play();
  267. this.actions[animName] = action;
  268. }
  269. update() {
  270. this.mixer.update(globals.deltaTime);
  271. }
  272. }
  273. class Player extends Component {
  274. constructor(gameObject) {
  275. super(gameObject);
  276. const model = models.knight;
  277. this.skinInstance = gameObject.addComponent(SkinInstance, model);
  278. this.skinInstance.setAnimation('Run');
  279. }
  280. }
  281. function init() {
  282. // hide the loading bar
  283. const loadingElem = document.querySelector('#loading');
  284. loadingElem.style.display = 'none';
  285. prepModelsAndAnimations();
  286. {
  287. const gameObject = gameObjectManager.createGameObject(scene, 'player');
  288. gameObject.addComponent(Player);
  289. }
  290. }
  291. function resizeRendererToDisplaySize(renderer) {
  292. const canvas = renderer.domElement;
  293. const width = canvas.clientWidth;
  294. const height = canvas.clientHeight;
  295. const needResize = canvas.width !== width || canvas.height !== height;
  296. if (needResize) {
  297. renderer.setSize(width, height, false);
  298. }
  299. return needResize;
  300. }
  301. let then = 0;
  302. function render(now) {
  303. // convert to seconds
  304. globals.time = now * 0.001;
  305. // make sure delta time isn't too big.
  306. globals.deltaTime = Math.min(globals.time - then, 1 / 20);
  307. then = globals.time;
  308. if (resizeRendererToDisplaySize(renderer)) {
  309. const canvas = renderer.domElement;
  310. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  311. camera.updateProjectionMatrix();
  312. }
  313. gameObjectManager.update();
  314. renderer.render(scene, camera);
  315. requestAnimationFrame(render);
  316. }
  317. requestAnimationFrame(render);
  318. }
  319. main();
  320. </script>
  321. </html>