webgl_animation_walk.html 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgl - animation - skinning</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <link type="text/css" rel="stylesheet" href="main.css">
  8. <style>
  9. a {
  10. color: #f00;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <div id="container"></div>
  16. <div id="info">
  17. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - Skeletal Animation Walking
  18. (model from <a href="https://www.mixamo.com/" target="_blank" rel="noopener">mixamo.com</a>)<br/>
  19. use arrows to control characters
  20. </div>
  21. <!-- Import maps polyfill -->
  22. <!-- Remove this when import maps will be widely supported -->
  23. <script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js"></script>
  24. <script type="importmap">
  25. {
  26. "imports": {
  27. "three": "../build/three.module.js",
  28. "three/addons/": "./jsm/"
  29. }
  30. }
  31. </script>
  32. <script type="module">
  33. import * as THREE from 'three';
  34. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  35. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  36. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  37. import { RGBELoader } from 'three/addons/loaders/RGBELoader.js';
  38. let scene, renderer, camera, floor, orbitControls;
  39. let group, followGroup, model, skeleton, mixer, clock;
  40. let actions;
  41. let settings = {
  42. show_skeleton:false,
  43. fixe_transition: true,
  44. };
  45. const PI = Math.PI;
  46. const PI90 = Math.PI / 2;
  47. const controls = {
  48. key:[0,0],
  49. ease : new THREE.Vector3(),
  50. position : new THREE.Vector3(),
  51. up : new THREE.Vector3(0, 1, 0),
  52. rotate: new THREE.Quaternion(),
  53. current:'Idle',
  54. fadeDuration:0.5,
  55. runVelocity:5,
  56. walkVelocity:1.8,
  57. rotateSpeed:0.05,
  58. floorDecale:0,
  59. };
  60. init();
  61. function init() {
  62. const container = document.getElementById( 'container' );
  63. camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 100 );
  64. camera.position.set( 0, 2, - 5 );
  65. //camera.lookAt( 0, 1, 0 );
  66. clock = new THREE.Clock();
  67. scene = new THREE.Scene();
  68. scene.background = new THREE.Color( 0x5e5d5d );
  69. scene.fog = new THREE.Fog( 0x5e5d5d, 2, 20 );
  70. group = new THREE.Group();
  71. scene.add(group);
  72. followGroup = new THREE.Group();
  73. scene.add(followGroup);
  74. /*const hemiLight = new THREE.HemisphereLight( 0xffffff, 0xb3602b, 0.5 );
  75. hemiLight.position.set( 0, 20, 0 );
  76. scene.add( hemiLight );*/
  77. const dirLight = new THREE.DirectionalLight( 0xffffff, 5 );
  78. dirLight.position.set( - 2, 5, - 3 );
  79. dirLight.castShadow = true;
  80. let cam = dirLight.shadow.camera;
  81. cam.top = cam.right = 2;
  82. cam.bottom = cam.left = - 2;
  83. cam.near = 3;
  84. cam.far = 8;
  85. dirLight.shadow.bias = -0.005;
  86. dirLight.shadow.radius = 4;
  87. followGroup.add( dirLight );
  88. followGroup.add( dirLight.target );
  89. //scene.add( new THREE.CameraHelper( cam ) );
  90. renderer = new THREE.WebGLRenderer( { antialias: true } );
  91. renderer.setPixelRatio( window.devicePixelRatio );
  92. renderer.setSize( window.innerWidth, window.innerHeight );
  93. renderer.toneMapping = THREE.ACESFilmicToneMapping;
  94. renderer.toneMappingExposure = 0.5;
  95. renderer.shadowMap.enabled = true;
  96. container.appendChild( renderer.domElement );
  97. orbitControls = new OrbitControls( camera, renderer.domElement );
  98. orbitControls.target.set( 0, 1, 0 );
  99. orbitControls.enableDamping = true;
  100. orbitControls.enablePan = false;
  101. orbitControls.maxPolarAngle = PI90 - 0.05;
  102. orbitControls.update();
  103. // EVENTS
  104. window.addEventListener( 'resize', onWindowResize );
  105. document.addEventListener( 'keydown', onKeyDown );
  106. document.addEventListener( 'keyup', onKeyUp );
  107. // DEMO
  108. new RGBELoader()
  109. .setPath( 'textures/equirectangular/' )
  110. .load( 'lobe.hdr', function ( texture ) {
  111. texture.mapping = THREE.EquirectangularReflectionMapping;
  112. scene.environment = texture;
  113. scene.environmentIntensity = 1.5;
  114. loadModel();
  115. addFloor();
  116. });
  117. }
  118. function addFloor() {
  119. let size = 50;
  120. let repeat = 16;
  121. const maxAnisotropy = renderer.capabilities.getMaxAnisotropy();
  122. const floorT = new THREE.TextureLoader().load( 'textures/floors/FloorsCheckerboard_S_Diffuse.jpg' );
  123. floorT.colorSpace = THREE.SRGBColorSpace;
  124. floorT.repeat.set( repeat, repeat );
  125. floorT.wrapS = floorT.wrapT = THREE.RepeatWrapping;
  126. floorT.anisotropy = maxAnisotropy;
  127. const floorN = new THREE.TextureLoader().load( 'textures/floors/FloorsCheckerboard_S_Normal.jpg' );
  128. floorN.repeat.set( repeat, repeat );
  129. floorN.wrapS = floorN.wrapT = THREE.RepeatWrapping;
  130. floorN.anisotropy = maxAnisotropy;
  131. let mat = new THREE.MeshStandardMaterial( { map:floorT, normalMap:floorN, normalScale:new THREE.Vector2(0.5,0.5), color: 0x404040, depthWrite: false, roughness:0.85 } )
  132. let g = new THREE.PlaneGeometry( size, size, 50, 50 );
  133. g.rotateX( -PI90 );
  134. floor = new THREE.Mesh( g, mat );
  135. floor.receiveShadow = true;
  136. scene.add( floor );
  137. controls.floorDecale = (size / repeat) * 4;
  138. const bulbGeometry = new THREE.SphereGeometry( 0.05, 16, 8 );
  139. let bulbLight = new THREE.PointLight( 0xffee88, 2, 500, 2 );
  140. let bulbMat = new THREE.MeshStandardMaterial( { emissive: 0xffffee, emissiveIntensity: 1, color: 0x000000 } );
  141. bulbLight.add( new THREE.Mesh( bulbGeometry, bulbMat ) );
  142. bulbLight.position.set( 1, 0.1, -3 );
  143. bulbLight.castShadow = true;
  144. floor.add( bulbLight );
  145. }
  146. function loadModel() {
  147. const loader = new GLTFLoader();
  148. loader.load( 'models/gltf/Soldier.glb', function ( gltf ) {
  149. model = gltf.scene;
  150. group.add( model );
  151. model.rotation.y = PI;
  152. group.rotation.y = PI;
  153. model.traverse( function ( object ) {
  154. if ( object.isMesh ){
  155. if( object.name == 'vanguard_Mesh' ){
  156. object.castShadow = true;
  157. object.receiveShadow = true;
  158. object.material.shadowSide = THREE.DoubleSide;
  159. //object.material.envMapIntensity = 0.5;
  160. object.material.metalness = 1.0;
  161. object.material.roughness = 0.2;
  162. object.material.color.set(1,1,1);
  163. object.material.metalnessMap = object.material.map;
  164. } else {
  165. object.material.metalness = 1;
  166. object.material.roughness = 0;
  167. object.material.transparent = true;
  168. object.material.opacity = 0.8;
  169. object.material.color.set(1,1,1);
  170. }
  171. }
  172. });
  173. //
  174. skeleton = new THREE.SkeletonHelper( model );
  175. skeleton.visible = false;
  176. scene.add( skeleton );
  177. //
  178. createPanel();
  179. //
  180. const animations = gltf.animations;
  181. mixer = new THREE.AnimationMixer( model );
  182. actions = {
  183. Idle:mixer.clipAction( animations[ 0 ] ),
  184. Walk:mixer.clipAction( animations[ 3 ] ),
  185. Run:mixer.clipAction( animations[ 1 ] )
  186. };
  187. for( let m in actions ){
  188. actions[m].enabled = true;
  189. actions[m].setEffectiveTimeScale( 1 );
  190. if(m!=='Idle') actions[m].setEffectiveWeight( 0 );
  191. }
  192. actions.Idle.play();
  193. animate();
  194. });
  195. }
  196. function updateCharacter( delta ) {
  197. const fade = controls.fadeDuration
  198. const key = controls.key;
  199. const up = controls.up;
  200. const ease = controls.ease;
  201. const rotate = controls.rotate;
  202. const position = controls.position;
  203. const azimut = orbitControls.getAzimuthalAngle();
  204. let active = key[0] === 0 && key[1] === 0 ? false : true;
  205. let play = active ? (key[2] ? 'Run' : 'Walk') : 'Idle';
  206. // change animation
  207. if ( controls.current != play ){
  208. const current = actions[play];
  209. const old = actions[controls.current];
  210. controls.current = play;
  211. if( settings.fixe_transition ){
  212. current.reset()
  213. current.weight = 1.0;
  214. current.stopFading()
  215. old.stopFading();
  216. // sycro if not idle
  217. if ( play !== 'Idle' ) current.time = old.time * ( current.getClip().duration / old.getClip().duration );
  218. old._scheduleFading( fade, old.getEffectiveWeight(), 0 );
  219. current._scheduleFading( fade, current.getEffectiveWeight(), 1 );
  220. current.play();
  221. } else {
  222. setWeight( current, 1.0 );
  223. old.fadeOut(fade);
  224. current.reset().fadeIn( fade ).play();
  225. }
  226. }
  227. // move object
  228. if ( controls.current !== 'Idle' ) {
  229. // run/walk velocity
  230. let velocity = controls.current == 'Run' ? controls.runVelocity : controls.walkVelocity;
  231. // direction with key
  232. ease.set( key[1], 0, key[0] ).multiplyScalar( velocity * delta );
  233. // calculate camera direction
  234. let angle = unwrapRad( Math.atan2( ease.x, ease.z ) + azimut );
  235. rotate.setFromAxisAngle( up, angle );
  236. // apply camera angle on ease
  237. controls.ease.applyAxisAngle( up, azimut );
  238. position.add( ease );
  239. camera.position.add( ease );
  240. group.position.copy( position );
  241. group.quaternion.rotateTowards( rotate, controls.rotateSpeed );
  242. orbitControls.target.copy( position ).add({x:0, y:1, z:0});
  243. followGroup.position.copy( position );
  244. // decale floor at infinie
  245. let dx = ( position.x - floor.position.x );
  246. let dz = ( position.z - floor.position.z );
  247. if( Math.abs(dx) > controls.floorDecale ) floor.position.x += dx;
  248. if( Math.abs(dz) > controls.floorDecale ) floor.position.z += dz;
  249. }
  250. mixer.update( delta );
  251. orbitControls.update();
  252. }
  253. function unwrapRad(r) {
  254. return Math.atan2(Math.sin(r), Math.cos(r));
  255. }
  256. function createPanel() {
  257. const panel = new GUI( { width: 310 } );
  258. panel.add( settings, 'show_skeleton' ).onChange( (b) => { skeleton.visible = b; } );
  259. panel.add( settings, 'fixe_transition' );
  260. }
  261. function setWeight( action, weight ) {
  262. action.enabled = true;
  263. action.setEffectiveTimeScale( 1 );
  264. action.setEffectiveWeight( weight );
  265. }
  266. function onKeyDown( event ) {
  267. const key = controls.key;
  268. switch ( event.code ) {
  269. case 'ArrowUp': case 'KeyW': case 'KeyZ': key[0] = -1; break;
  270. case 'ArrowDown': case 'KeyS': key[0] = 1; break;
  271. case 'ArrowLeft': case 'KeyA': case 'KeyQ': key[1] = -1; break;
  272. case 'ArrowRight': case 'KeyD': key[1] = 1; break;
  273. case 'ShiftLeft' : case 'ShiftRight' : key[2] = 1; break;
  274. }
  275. }
  276. function onKeyUp( event ) {
  277. const key = controls.key;
  278. switch ( event.code ) {
  279. case 'ArrowUp': case 'KeyW': case 'KeyZ': key[0] = key[0]<0 ? 0:key[0]; break;
  280. case 'ArrowDown': case 'KeyS': key[0] = key[0]>0 ? 0:key[0]; break;
  281. case 'ArrowLeft': case 'KeyA': case 'KeyQ': key[1] = key[1]<0 ? 0:key[1]; break;
  282. case 'ArrowRight': case 'KeyD': key[1] = key[1]>0 ? 0:key[1]; break;
  283. case 'ShiftLeft' : case 'ShiftRight' : key[2] = 0; break;
  284. }
  285. }
  286. function onWindowResize() {
  287. camera.aspect = window.innerWidth / window.innerHeight;
  288. camera.updateProjectionMatrix();
  289. renderer.setSize( window.innerWidth, window.innerHeight );
  290. }
  291. function animate() {
  292. // Render loop
  293. requestAnimationFrame( animate );
  294. let delta = clock.getDelta();
  295. updateCharacter( delta );
  296. renderer.render( scene, camera );
  297. }
  298. </script>
  299. </body>
  300. </html>
粤ICP备19079148号