physics_rapier_terrain.html 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>Rapier.js terrain heightfield demo</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="Rapier.js terrain heightfield demo">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/physics_rapier_terrain.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/physics_rapier_terrain.jpg">
  11. <link type="text/css" rel="stylesheet" href="main.css">
  12. <style>
  13. body {
  14. color: #333;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="container"></div>
  20. <div id="info">Rapier.js physics terrain heightfield demo</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 Stats from 'three/addons/libs/stats.module.js';
  32. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  33. import { RapierPhysics } from 'three/addons/physics/RapierPhysics.js';
  34. // Heightfield parameters
  35. const terrainWidthExtents = 100;
  36. const terrainDepthExtents = 100;
  37. const terrainWidth = 128;
  38. const terrainDepth = 128;
  39. const terrainHalfWidth = terrainWidth / 2;
  40. const terrainHalfDepth = terrainDepth / 2;
  41. const terrainMaxHeight = 8;
  42. const terrainMinHeight = - 2;
  43. // Graphics variables
  44. let container, stats;
  45. let camera, scene, renderer;
  46. let terrainMesh;
  47. const timer = new THREE.Timer();
  48. timer.connect( document );
  49. // Physics variables
  50. let physics;
  51. const dynamicObjects = [];
  52. let heightData = null;
  53. let time = 0;
  54. const objectTimePeriod = 3;
  55. let timeNextSpawn = time + objectTimePeriod;
  56. const maxNumObjects = 30;
  57. init();
  58. async function init() {
  59. heightData = generateHeight( terrainWidth, terrainDepth, terrainMinHeight, terrainMaxHeight );
  60. initGraphics();
  61. await initPhysics();
  62. // Start animation loop only after physics is initialized
  63. renderer.setAnimationLoop( animate );
  64. }
  65. function initGraphics() {
  66. container = document.getElementById( 'container' );
  67. renderer = new THREE.WebGLRenderer( { antialias: true } );
  68. renderer.setPixelRatio( window.devicePixelRatio );
  69. renderer.setSize( window.innerWidth, window.innerHeight );
  70. // Remove setAnimationLoop from here since we'll start it after physics init
  71. renderer.shadowMap.enabled = true;
  72. container.appendChild( renderer.domElement );
  73. stats = new Stats();
  74. stats.domElement.style.position = 'absolute';
  75. stats.domElement.style.top = '0px';
  76. container.appendChild( stats.domElement );
  77. camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.2, 2000 );
  78. scene = new THREE.Scene();
  79. scene.background = new THREE.Color( 0xbfd1e5 );
  80. camera.position.y = heightData[ terrainHalfWidth + terrainHalfDepth * terrainWidth ] * ( terrainMaxHeight - terrainMinHeight ) + 5;
  81. camera.position.z = terrainDepthExtents / 2;
  82. camera.lookAt( 0, 0, 0 );
  83. const controls = new OrbitControls( camera, renderer.domElement );
  84. controls.enableZoom = false;
  85. const geometry = new THREE.PlaneGeometry( terrainWidthExtents, terrainDepthExtents, terrainWidth - 1, terrainDepth - 1 );
  86. geometry.rotateX( - Math.PI / 2 );
  87. const vertices = geometry.attributes.position.array;
  88. for ( let i = 0, j = 0, l = vertices.length; i < l; i ++, j += 3 ) {
  89. vertices[ j + 1 ] = heightData[ i ];
  90. }
  91. geometry.computeVertexNormals();
  92. const groundMaterial = new THREE.MeshPhongMaterial( { color: 0xC7C7C7 } );
  93. terrainMesh = new THREE.Mesh( geometry, groundMaterial );
  94. terrainMesh.receiveShadow = true;
  95. terrainMesh.castShadow = true;
  96. scene.add( terrainMesh );
  97. const textureLoader = new THREE.TextureLoader();
  98. textureLoader.load( 'textures/grid.png', function ( texture ) {
  99. texture.wrapS = THREE.RepeatWrapping;
  100. texture.wrapT = THREE.RepeatWrapping;
  101. texture.repeat.set( terrainWidth - 1, terrainDepth - 1 );
  102. groundMaterial.map = texture;
  103. groundMaterial.needsUpdate = true;
  104. } );
  105. const ambientLight = new THREE.AmbientLight( 0xbbbbbb );
  106. scene.add( ambientLight );
  107. const light = new THREE.DirectionalLight( 0xffffff, 3 );
  108. light.position.set( 100, 100, 50 );
  109. light.castShadow = true;
  110. const dLight = 200;
  111. const sLight = dLight * 0.25;
  112. light.shadow.camera.left = - sLight;
  113. light.shadow.camera.right = sLight;
  114. light.shadow.camera.top = sLight;
  115. light.shadow.camera.bottom = - sLight;
  116. light.shadow.camera.near = dLight / 30;
  117. light.shadow.camera.far = dLight;
  118. light.shadow.mapSize.x = 1024 * 2;
  119. light.shadow.mapSize.y = 1024 * 2;
  120. scene.add( light );
  121. window.addEventListener( 'resize', onWindowResize );
  122. }
  123. function onWindowResize() {
  124. camera.aspect = window.innerWidth / window.innerHeight;
  125. camera.updateProjectionMatrix();
  126. renderer.setSize( window.innerWidth, window.innerHeight );
  127. }
  128. async function initPhysics() {
  129. physics = await RapierPhysics();
  130. // Create the terrain body using RapierPhysics module
  131. physics.addHeightfield( terrainMesh, terrainWidth - 1, terrainDepth - 1, heightData, { x: terrainWidthExtents, y: 1.0, z: terrainDepthExtents } );
  132. // Continue with adding other dynamic objects as needed
  133. }
  134. function generateHeight( width, depth, minHeight, maxHeight ) {
  135. const size = width * depth;
  136. const data = new Float32Array( size );
  137. const hRange = maxHeight - minHeight;
  138. const w2 = width / 2;
  139. const d2 = depth / 2;
  140. const phaseMult = 12;
  141. let p = 0;
  142. for ( let j = 0; j < depth; j ++ ) {
  143. for ( let i = 0; i < width; i ++ ) {
  144. const radius = Math.sqrt( Math.pow( ( i - w2 ) / w2, 2.0 ) + Math.pow( ( j - d2 ) / d2, 2.0 ) );
  145. const height = ( Math.sin( radius * phaseMult ) + 1 ) * 0.5 * hRange + minHeight;
  146. data[ p ] = height;
  147. p ++;
  148. }
  149. }
  150. return data;
  151. }
  152. function generateObject() {
  153. const numTypes = 3; // cones not working
  154. const objectType = Math.ceil( Math.random() * numTypes );
  155. let threeObject = null;
  156. const objectSize = 3;
  157. let radius, height;
  158. switch ( objectType ) {
  159. case 1: // Sphere
  160. radius = 1 + Math.random() * objectSize;
  161. threeObject = new THREE.Mesh( new THREE.SphereGeometry( radius, 20, 20 ), createObjectMaterial() );
  162. break;
  163. case 2: // Box
  164. const sx = 1 + Math.random() * objectSize;
  165. const sy = 1 + Math.random() * objectSize;
  166. const sz = 1 + Math.random() * objectSize;
  167. threeObject = new THREE.Mesh( new THREE.BoxGeometry( sx, sy, sz, 1, 1, 1 ), createObjectMaterial() );
  168. break;
  169. case 3: // Cylinder
  170. radius = 1 + Math.random() * objectSize;
  171. height = 1 + Math.random() * objectSize;
  172. threeObject = new THREE.Mesh( new THREE.CylinderGeometry( radius, radius, height, 20, 1 ), createObjectMaterial() );
  173. break;
  174. default: // Cone
  175. radius = 1 + Math.random() * objectSize;
  176. height = 2 + Math.random() * objectSize;
  177. threeObject = new THREE.Mesh( new THREE.ConeGeometry( radius, height, 20, 2 ), createObjectMaterial() );
  178. break;
  179. }
  180. // Position objects higher and with more randomization to prevent clustering
  181. threeObject.position.set(
  182. ( Math.random() - 0.5 ) * terrainWidth * 0.6,
  183. terrainMaxHeight + objectSize + 15 + Math.random() * 5, // Even higher with randomization
  184. ( Math.random() - 0.5 ) * terrainDepth * 0.6
  185. );
  186. const mass = objectSize * 5;
  187. const restitution = 0.3; // Add some bounciness
  188. // Add to scene first
  189. scene.add( threeObject );
  190. // Add physics to the object
  191. physics.addMesh( threeObject, mass, restitution );
  192. // Store the object for later reference
  193. dynamicObjects.push( threeObject );
  194. // Force a small delay before adding the next object
  195. timeNextSpawn = time + 0.5;
  196. threeObject.receiveShadow = true;
  197. threeObject.castShadow = true;
  198. }
  199. function createObjectMaterial() {
  200. const c = Math.floor( Math.random() * ( 1 << 24 ) );
  201. return new THREE.MeshPhongMaterial( { color: c } );
  202. }
  203. function animate() {
  204. timer.update();
  205. render();
  206. stats.update();
  207. }
  208. function render() {
  209. const deltaTime = timer.getDelta();
  210. // Generate new objects with a delay between them
  211. if ( dynamicObjects.length < maxNumObjects && time > timeNextSpawn ) {
  212. // Generate object directly in this frame
  213. generateObject();
  214. // timeNextSpawn is now set in generateObject()
  215. }
  216. // Clean up objects that have fallen off the terrain
  217. for ( let i = dynamicObjects.length - 1; i >= 0; i -- ) {
  218. const obj = dynamicObjects[ i ];
  219. if ( obj.position.y < terrainMinHeight - 10 ) {
  220. // Remove from scene and physics world
  221. scene.remove( obj );
  222. dynamicObjects.splice( i, 1 );
  223. }
  224. }
  225. updatePhysics();
  226. renderer.render( scene, camera );
  227. time += deltaTime;
  228. }
  229. function updatePhysics() {
  230. // Check for objects that might need help with physics
  231. for ( let i = 0, il = dynamicObjects.length; i < il; i ++ ) {
  232. const objThree = dynamicObjects[ i ];
  233. // If object is not moving but should be (based on height), try to fix it
  234. if ( objThree.position.y > 1.0 ) {
  235. // Check if physics body exists
  236. if ( objThree.userData && objThree.userData.physics && objThree.userData.physics.body ) {
  237. const body = objThree.userData.physics.body;
  238. // Make sure body is awake
  239. if ( typeof body.wakeUp === 'function' ) {
  240. body.wakeUp();
  241. }
  242. // Check velocity and apply impulse if needed
  243. if ( typeof body.linvel === 'function' ) {
  244. const velocity = body.linvel();
  245. const speed = Math.sqrt( velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z );
  246. // If object is very slow, give it a stronger impulse
  247. if ( speed < 0.5 ) {
  248. body.applyImpulse( { x: 0, y: - 2.0, z: 0 }, true );
  249. }
  250. }
  251. } else {
  252. // If the object doesn't have a physics body but should, recreate it
  253. const mass = 5; // Default mass
  254. const restitution = 0.3; // Default restitution
  255. // Recreate physics for the object
  256. physics.addMesh( objThree, mass, restitution );
  257. }
  258. }
  259. }
  260. }
  261. </script>
  262. </body>
  263. </html>
粤ICP备19079148号