threejs-game-just-player.html 8.9 KB

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