game-just-player.html 9.0 KB

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