webgl_animation_walk.html 11 KB

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