webgl_animation_walk.html 11 KB

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