game-just-player.html 9.2 KB

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