game-just-player.html 8.9 KB

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