Pārlūkot izejas kodu

RapierPhysics: Add `applyImpulse()`. (#33459)

Michael Herzog 1 mēnesi atpakaļ
vecāks
revīzija
083a11c067

+ 27 - 2
examples/jsm/physics/RapierPhysics.js

@@ -281,6 +281,20 @@ async function RapierPhysics() {
 
 	}
 
+	function applyImpulse( mesh, impulse, index = 0 ) {
+
+		let { body } = meshMap.get( mesh );
+
+		if ( mesh.isInstancedMesh ) {
+
+			body = body[ index ];
+
+		}
+
+		body.applyImpulse( impulse, true );
+
+	}
+
 	function addHeightfield( mesh, width, depth, heights, scale ) {
 
 		const shape = RAPIER.ColliderDesc.heightfield( width, depth, heights, scale );
@@ -414,7 +428,7 @@ async function RapierPhysics() {
 
 		/**
 		 * Adds a heightfield terrain to the physics simulation.
-		 * 
+		 *
 		 * @method
 		 * @name RapierPhysics#addHeightfield
 		 * @param {Mesh} mesh - The Three.js mesh representing the terrain.
@@ -427,7 +441,18 @@ async function RapierPhysics() {
 		 * @param {number} scale.z - Scale factor for depth.
 		 * @returns {RigidBody} The created Rapier rigid body for the heightfield.
 		 */
-		addHeightfield: addHeightfield
+		addHeightfield: addHeightfield,
+
+		/**
+		 * Applies an impulse to the given mesh which is part of the physics simulation.
+		 *
+		 * @method
+		 * @name RapierPhysics#applyImpulse
+		 * @param {Mesh} mesh - The mesh to apply the impulse to.
+		 * @param {Vector3} impulse - The impulse to apply.
+		 * @param {number} [index=0] - If the mesh is instanced, the index represents the instanced ID.
+		 */
+		applyImpulse: applyImpulse
 
 	};
 

+ 24 - 1
examples/physics_rapier_instancing.html

@@ -9,7 +9,8 @@
 	<body>
 
 		<div id="info">
-			<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> physics - <a href="https://github.com/dimforge/rapier.js" target="_blank">rapier</a> instancing
+			<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> physics - <a href="https://github.com/dimforge/rapier.js" target="_blank">rapier</a> instancing<br />
+			<button id="shake" style="margin-top: 25px;">SHAKE</button>
 		</div>
 
 		<script type="importmap">
@@ -140,6 +141,28 @@
 				controls.target.y = 0.5;
 				controls.update();
 
+				document.querySelector( 'button#shake' ).addEventListener( 'click', () => {
+
+					const impulse = new THREE.Vector3();
+
+					for ( let i = 0; i < spheres.count; i ++ ) {
+
+						impulse.set( ( Math.random() - 0.5 ) * 5, Math.random() * 5, ( Math.random() - 0.5 ) * 5 );
+
+						physics.applyImpulse( spheres, impulse, i );
+
+					}
+
+					for ( let i = 0; i < boxes.count; i ++ ) {
+
+						impulse.set( ( Math.random() - 0.5 ) * 5, Math.random() * 5, ( Math.random() - 0.5 ) * 5 );
+
+						physics.applyImpulse( boxes, impulse, i );
+
+					}
+
+				} );
+
 				setInterval( () => {
 
 					let index = Math.floor( Math.random() * boxes.count );

粤ICP备19079148号