Browse Source

RapierPhysics: Add removeMesh() (#31296)

* RapierPhysics: Add removeMesh()

* Update RapierPhysics.js

Fix JSDoc.

---------

Co-authored-by: Michael Herzog <michael.herzog@human-interactive.org>
林炳权 11 months ago
parent
commit
7858b59e2b
2 changed files with 63 additions and 4 deletions
  1. 43 1
      examples/jsm/physics/RapierPhysics.js
  2. 20 3
      examples/physics_rapier_basic.html

+ 43 - 1
examples/jsm/physics/RapierPhysics.js

@@ -1,6 +1,6 @@
 import { Clock, Vector3, Quaternion, Matrix4 } from 'three';
 
-const RAPIER_PATH = 'https://cdn.skypack.dev/@dimforge/rapier3d-compat@0.12.0';
+const RAPIER_PATH = 'https://cdn.skypack.dev/@dimforge/rapier3d-compat@0.17.3';
 
 const frameRate = 60;
 
@@ -149,6 +149,39 @@ async function RapierPhysics() {
 
 	}
 
+	function removeMesh( mesh ) {
+
+		const index = meshes.indexOf( mesh );
+
+		if ( index !== - 1 ) {
+
+			meshes.splice( index, 1 );
+			meshMap.delete( mesh );
+
+			if ( ! mesh.userData.physics ) return;
+
+			const body = mesh.userData.physics.body;
+
+			if ( ! body ) return;
+
+			if ( Array.isArray( body ) ) {
+
+				for ( let i = 0; i < body.length; i ++ ) {
+
+					world.removeRigidBody( body[ i ] );
+
+				}
+
+			} else {
+
+				world.removeRigidBody( body );
+
+			}
+
+		}
+
+	}
+
 	function createInstancedBody( mesh, mass, shape ) {
 
 		const array = mesh.instanceMatrix.array;
@@ -306,6 +339,15 @@ async function RapierPhysics() {
 		 */
 		addMesh: addMesh,
 
+		/**
+		 * Removes the given mesh from this physics simulation.
+		 *
+		 * @method
+		 * @name RapierPhysics#removeMesh
+		 * @param {Mesh} mesh The mesh to remove.
+		 */
+		removeMesh: removeMesh,
+
 		/**
 		 * Set the position of the given mesh which is part of the physics simulation. Calling this
 		 * method will reset the current simulated velocity of the mesh.

+ 20 - 3
examples/physics_rapier_basic.html

@@ -34,7 +34,7 @@
 			import { RapierHelper } from 'three/addons/helpers/RapierHelper.js';
 			import Stats from 'three/addons/libs/stats.module.js';
 
-			let camera, scene, renderer, stats;
+			let camera, scene, renderer, stats, controls;
 			let physics, physicsHelper;
 
 			init();
@@ -77,7 +77,8 @@
 				document.body.appendChild( renderer.domElement );
 				renderer.setAnimationLoop( animate );
 
-				const controls = new OrbitControls( camera, renderer.domElement );
+				controls = new OrbitControls( camera, renderer.domElement );
+				controls.enableDamping = true;
 				controls.target = new THREE.Vector3( 0, 2, 0 );
 				controls.update();
 
@@ -156,11 +157,27 @@
 
 			}
 
-
 			function animate() {
 
+				for ( const object of scene.children ) {
+
+					if ( object.isMesh ) {
+
+						if ( object.position.y < - 10 ) {
+
+							scene.remove( object );
+							physics.removeMesh( object );
+
+						}
+			
+					}
+
+				}
+
 				if ( physicsHelper ) physicsHelper.update();
 
+				controls.update();
+
 				renderer.render( scene, camera );
 
 				stats.update();

粤ICP备19079148号