webgl_animation_walk.html 11 KB

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