load-gltf-animated-cars.html 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 - Load .GLTF - Animated Cars</title>
  8. <style>
  9. html, body {
  10. margin: 0;
  11. height: 100%;
  12. }
  13. #c {
  14. width: 100%;
  15. height: 100%;
  16. display: block;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <canvas id="c"></canvas>
  22. </body>
  23. <script type="importmap">
  24. {
  25. "imports": {
  26. "three": "../../build/three.module.js",
  27. "three/addons/": "../../examples/jsm/"
  28. }
  29. }
  30. </script>
  31. <script type="module">
  32. import * as THREE from 'three';
  33. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  34. import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
  35. function main() {
  36. const canvas = document.querySelector( '#c' );
  37. const renderer = new THREE.WebGLRenderer( { antialias: true, canvas } );
  38. const fov = 45;
  39. const aspect = 2; // the canvas default
  40. const near = 0.1;
  41. const far = 100;
  42. const camera = new THREE.PerspectiveCamera( fov, aspect, near, far );
  43. camera.position.set( 0, 10, 20 );
  44. const controls = new OrbitControls( camera, canvas );
  45. controls.target.set( 0, 5, 0 );
  46. controls.update();
  47. const scene = new THREE.Scene();
  48. scene.background = new THREE.Color( 'black' );
  49. {
  50. const planeSize = 40;
  51. const loader = new THREE.TextureLoader();
  52. const texture = loader.load( 'resources/images/checker.png' );
  53. texture.wrapS = THREE.RepeatWrapping;
  54. texture.wrapT = THREE.RepeatWrapping;
  55. texture.magFilter = THREE.NearestFilter;
  56. texture.colorSpace = THREE.SRGBColorSpace;
  57. const repeats = planeSize / 2;
  58. texture.repeat.set( repeats, repeats );
  59. const planeGeo = new THREE.PlaneGeometry( planeSize, planeSize );
  60. const planeMat = new THREE.MeshPhongMaterial( {
  61. map: texture,
  62. side: THREE.DoubleSide,
  63. } );
  64. const mesh = new THREE.Mesh( planeGeo, planeMat );
  65. mesh.rotation.x = Math.PI * - .5;
  66. scene.add( mesh );
  67. }
  68. {
  69. const skyColor = 0xB1E1FF; // light blue
  70. const groundColor = 0xB97A20; // brownish orange
  71. const intensity = 2;
  72. const light = new THREE.HemisphereLight( skyColor, groundColor, intensity );
  73. scene.add( light );
  74. }
  75. {
  76. const color = 0xFFFFFF;
  77. const intensity = 2.5;
  78. const light = new THREE.DirectionalLight( color, intensity );
  79. light.position.set( 5, 10, 2 );
  80. scene.add( light );
  81. scene.add( light.target );
  82. }
  83. function frameArea( sizeToFitOnScreen, boxSize, boxCenter, camera ) {
  84. const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
  85. const halfFovY = THREE.MathUtils.degToRad( camera.fov * .5 );
  86. const distance = halfSizeToFitOnScreen / Math.tan( halfFovY );
  87. // compute a unit vector that points in the direction the camera is now
  88. // in the xz plane from the center of the box
  89. const direction = ( new THREE.Vector3() )
  90. .subVectors( camera.position, boxCenter )
  91. .multiply( new THREE.Vector3( 1, 0, 1 ) )
  92. .normalize();
  93. // move the camera to a position distance units way from the center
  94. // in whatever direction the camera was from the center already
  95. camera.position.copy( direction.multiplyScalar( distance ).add( boxCenter ) );
  96. // pick some near and far values for the frustum that
  97. // will contain the box.
  98. camera.near = boxSize / 100;
  99. camera.far = boxSize * 100;
  100. camera.updateProjectionMatrix();
  101. // point the camera to look at the center of the box
  102. camera.lookAt( boxCenter.x, boxCenter.y, boxCenter.z );
  103. }
  104. let curve;
  105. let curveObject;
  106. {
  107. const controlPoints = [
  108. [ 1.118281, 5.115846, - 3.681386 ],
  109. [ 3.948875, 5.115846, - 3.641834 ],
  110. [ 3.960072, 5.115846, - 0.240352 ],
  111. [ 3.985447, 5.115846, 4.585005 ],
  112. [ - 3.793631, 5.115846, 4.585006 ],
  113. [ - 3.826839, 5.115846, - 14.736200 ],
  114. [ - 14.542292, 5.115846, - 14.765865 ],
  115. [ - 14.520929, 5.115846, - 3.627002 ],
  116. [ - 5.452815, 5.115846, - 3.634418 ],
  117. [ - 5.467251, 5.115846, 4.549161 ],
  118. [ - 13.266233, 5.115846, 4.567083 ],
  119. [ - 13.250067, 5.115846, - 13.499271 ],
  120. [ 4.081842, 5.115846, - 13.435463 ],
  121. [ 4.125436, 5.115846, - 5.334928 ],
  122. [ - 14.521364, 5.115846, - 5.239871 ],
  123. [ - 14.510466, 5.115846, 5.486727 ],
  124. [ 5.745666, 5.115846, 5.510492 ],
  125. [ 5.787942, 5.115846, - 14.728308 ],
  126. [ - 5.423720, 5.115846, - 14.761919 ],
  127. [ - 5.373599, 5.115846, - 3.704133 ],
  128. [ 1.004861, 5.115846, - 3.641834 ],
  129. ];
  130. const p0 = new THREE.Vector3();
  131. const p1 = new THREE.Vector3();
  132. curve = new THREE.CatmullRomCurve3(
  133. controlPoints.map( ( p, ndx ) => {
  134. p0.set( ...p );
  135. p1.set( ...controlPoints[ ( ndx + 1 ) % controlPoints.length ] );
  136. return [
  137. ( new THREE.Vector3() ).copy( p0 ),
  138. ( new THREE.Vector3() ).lerpVectors( p0, p1, 0.1 ),
  139. ( new THREE.Vector3() ).lerpVectors( p0, p1, 0.9 ),
  140. ];
  141. } ).flat(),
  142. true,
  143. );
  144. {
  145. const points = curve.getPoints( 250 );
  146. const geometry = new THREE.BufferGeometry().setFromPoints( points );
  147. const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  148. curveObject = new THREE.Line( geometry, material );
  149. curveObject.scale.set( 100, 100, 100 );
  150. curveObject.position.y = - 621;
  151. curveObject.visible = false;
  152. material.depthTest = false;
  153. curveObject.renderOrder = 1;
  154. scene.add( curveObject );
  155. }
  156. }
  157. const cars = [];
  158. {
  159. const gltfLoader = new GLTFLoader();
  160. gltfLoader.load( 'resources/models/cartoon_lowpoly_small_city_free_pack/scene.gltf', ( gltf ) => {
  161. const root = gltf.scene;
  162. scene.add( root );
  163. const loadedCars = root.getObjectByName( 'Cars' );
  164. const fixes = [
  165. { prefix: 'Car_08', y: 0, rot: [ Math.PI * .5, 0, Math.PI * .5 ], },
  166. { prefix: 'CAR_03', y: 33, rot: [ 0, Math.PI, 0 ], },
  167. { prefix: 'Car_04', y: 40, rot: [ 0, Math.PI, 0 ], },
  168. ];
  169. root.updateMatrixWorld();
  170. for ( const car of loadedCars.children.slice() ) {
  171. const fix = fixes.find( fix => car.name.startsWith( fix.prefix ) );
  172. const obj = new THREE.Object3D();
  173. car.position.set( 0, fix.y, 0 );
  174. car.rotation.set( ...fix.rot );
  175. obj.add( car );
  176. scene.add( obj );
  177. cars.push( obj );
  178. }
  179. // compute the box that contains all the stuff
  180. // from root and below
  181. const box = new THREE.Box3().setFromObject( root );
  182. const boxSize = box.getSize( new THREE.Vector3() ).length();
  183. const boxCenter = box.getCenter( new THREE.Vector3() );
  184. // set the camera to frame the box
  185. frameArea( boxSize * 0.5, boxSize, boxCenter, camera );
  186. // update the Trackball controls to handle the new size
  187. controls.maxDistance = boxSize * 10;
  188. controls.target.copy( boxCenter );
  189. controls.update();
  190. } );
  191. }
  192. function resizeRendererToDisplaySize( renderer ) {
  193. const canvas = renderer.domElement;
  194. const width = canvas.clientWidth;
  195. const height = canvas.clientHeight;
  196. const needResize = canvas.width !== width || canvas.height !== height;
  197. if ( needResize ) {
  198. renderer.setSize( width, height, false );
  199. }
  200. return needResize;
  201. }
  202. // create 2 Vector3s we can use for path calculations
  203. const carPosition = new THREE.Vector3();
  204. const carTarget = new THREE.Vector3();
  205. function render( time ) {
  206. time *= 0.001; // convert to seconds
  207. if ( resizeRendererToDisplaySize( renderer ) ) {
  208. const canvas = renderer.domElement;
  209. camera.aspect = canvas.clientWidth / canvas.clientHeight;
  210. camera.updateProjectionMatrix();
  211. }
  212. {
  213. const pathTime = time * .01;
  214. const targetOffset = 0.01;
  215. cars.forEach( ( car, ndx ) => {
  216. // a number between 0 and 1 to evenly space the cars
  217. const u = pathTime + ndx / cars.length;
  218. // get the first point
  219. curve.getPointAt( u % 1, carPosition );
  220. carPosition.applyMatrix4( curveObject.matrixWorld );
  221. // get a second point slightly further down the curve
  222. curve.getPointAt( ( u + targetOffset ) % 1, carTarget );
  223. carTarget.applyMatrix4( curveObject.matrixWorld );
  224. // put the car at the first point (temporarily)
  225. car.position.copy( carPosition );
  226. // point the car the second point
  227. car.lookAt( carTarget );
  228. // put the car between the 2 points
  229. car.position.lerpVectors( carPosition, carTarget, 0.5 );
  230. } );
  231. }
  232. renderer.render( scene, camera );
  233. requestAnimationFrame( render );
  234. }
  235. requestAnimationFrame( render );
  236. }
  237. main();
  238. </script>
  239. </html>