Skip to content

Added additional Rapier physics examples #30818

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 19 commits into from
Apr 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion examples/files.json
Original file line number Diff line number Diff line change
Expand Up @@ -502,7 +502,11 @@
"physics_ammo_terrain",
"physics_ammo_volume",
"physics_jolt_instancing",
"physics_rapier_instancing"
"physics_rapier_basic",
"physics_rapier_instancing",
"physics_rapier_joints",
"physics_rapier_character_controller",
"physics_rapier_vehicle_controller"
],
"misc": [
"misc_animation_groups",
Expand Down
58 changes: 58 additions & 0 deletions examples/jsm/helpers/RapierHelper.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { LineSegments, LineBasicMaterial, BufferAttribute } from 'three';
/**
* This class displays all Rapier Colliders in outline.
*
* @augments LineSegments
*/
class RapierHelper extends LineSegments {

/**
* Constructs a new Rapier debug helper.
*
* @param {RAPIER.world} world - The Rapier world to visualize.
*/
constructor( world ) {

super();

/**
* The Rapier world to visualize.
*
* @type {RAPIER.world}
*/
this.world = world;

this.material = new LineBasicMaterial( { vertexColors: true } );
this.frustumCulled = false;

}

/**
* Call this in the render loop to update the outlines.
*/
update() {

const { vertices, colors } = this.world.debugRender();

this.geometry.deleteAttribute( 'position' );
this.geometry.deleteAttribute( 'color' );

this.geometry.setAttribute( 'position', new BufferAttribute( vertices, 3 ) );
this.geometry.setAttribute( 'color', new BufferAttribute( colors, 4 ) );

}

/**
* Frees the GPU-related resources allocated by this instance. Call this
* method whenever this instance is no longer used in your app.
*/
dispose() {

this.geometry.dispose();
this.material.dispose();

}

}

export { RapierHelper };
20 changes: 20 additions & 0 deletions examples/jsm/physics/RapierPhysics.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,20 @@ function getShape( geometry ) {
const radius = parameters.radius !== undefined ? parameters.radius : 1;
return RAPIER.ColliderDesc.ball( radius );

} else if ( geometry.type === 'CylinderGeometry' ) {

const radius = parameters.radiusBottom !== undefined ? parameters.radiusBottom : 0.5;
const length = parameters.length !== undefined ? parameters.length : 0.5;

return RAPIER.ColliderDesc.cylinder( length / 2, radius );

} else if ( geometry.type === 'CapsuleGeometry' ) {

const radius = parameters.radius !== undefined ? parameters.radius : 0.5;
const length = parameters.length !== undefined ? parameters.length : 0.5;

return RAPIER.ColliderDesc.capsule( length / 2, radius );

} else if ( geometry.type === 'BufferGeometry' ) {

const vertices = [];
Expand Down Expand Up @@ -121,6 +135,10 @@ async function RapierPhysics() {
? createInstancedBody( mesh, mass, shape )
: createBody( mesh.position, mesh.quaternion, mass, shape );

if ( ! mesh.userData.physics ) mesh.userData.physics = {};

mesh.userData.physics.body = body;

if ( mass > 0 ) {

meshes.push( mesh );
Expand Down Expand Up @@ -242,6 +260,8 @@ async function RapierPhysics() {
setInterval( step, 1000 / frameRate );

return {
RAPIER,
world,
/**
* Adds the given scene to this physics simulation. Only meshes with a
* `physics` object in their {@link Object3D#userData} field will be honored.
Expand Down
172 changes: 172 additions & 0 deletions examples/physics_rapier_basic.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js physics - rapier3d basic</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link type="text/css" rel="stylesheet" href="main.css">
<style>
body {
color: #333;
}
</style>
</head>
<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> basic
</div>

<script type="importmap">
{
"imports": {
"three": "../build/three.module.js",
"three/addons/": "./jsm/"
}
}
</script>

<script type="module">

import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RapierPhysics } from 'three/addons/physics/RapierPhysics.js';
import { RapierHelper } from 'three/addons/helpers/RapierHelper.js';
import Stats from 'three/addons/libs/stats.module.js';

let camera, scene, renderer, stats;
let physics, physicsHelper;

init();

async function init() {

scene = new THREE.Scene();
scene.background = new THREE.Color( 0xbfd1e5 );

camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 100 );
camera.position.set( 0, 3, 10 );

const ambient = new THREE.HemisphereLight( 0x555555, 0xFFFFFF );

scene.add( ambient );

const light = new THREE.DirectionalLight( 0xffffff, 4 );

light.position.set( 0, 12.5, 12.5 );
light.castShadow = true;
light.shadow.radius = 3;
light.shadow.blurSamples = 8;
light.shadow.mapSize.width = 1024;
light.shadow.mapSize.height = 1024;

const size = 10;
light.shadow.camera.left = - size;
light.shadow.camera.bottom = - size;
light.shadow.camera.right = size;
light.shadow.camera.top = size;
light.shadow.camera.near = 1;
light.shadow.camera.far = 50;

scene.add( light );

renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.shadowMap.enabled = true;
document.body.appendChild( renderer.domElement );
renderer.setAnimationLoop( animate );

const controls = new OrbitControls( camera, renderer.domElement );
controls.target = new THREE.Vector3( 0, 2, 0 );
controls.update();

const geometry = new THREE.BoxGeometry( 10, 0.5, 10 );
const material = new THREE.MeshStandardMaterial( { color: 0xFFFFFF } );

const floor = new THREE.Mesh( geometry, material );
floor.receiveShadow = true;

floor.position.y = - 0.25;
floor.userData.physics = { mass: 0 };

scene.add( floor );

new THREE.TextureLoader().load( 'textures/grid.png', function ( texture ) {

texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set( 20, 20 );
floor.material.map = texture;
floor.material.needsUpdate = true;

} );

stats = new Stats();
document.body.appendChild( stats.dom );

initPhysics();

onWindowResize();

window.addEventListener( 'resize', onWindowResize, false );

}

async function initPhysics() {

//Initialize physics engine using the script in the jsm/physics folder
physics = await RapierPhysics();

physics.addScene( scene );

addBody( );

//Optionally display collider outlines
physicsHelper = new RapierHelper( physics.world );
scene.add( physicsHelper );

setInterval( addBody, 1000 );

}

function addBody( ) {

const geometry = ( Math.random() > 0.5 ) ? new THREE.SphereGeometry( 0.5 ) : new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshStandardMaterial( { color: Math.floor( Math.random() * 0xFFFFFF ) } );

const mesh = new THREE.Mesh( geometry, material );
mesh.castShadow = true;

mesh.position.set( Math.random() * 2 - 1, Math.random() * 3 + 6, Math.random() * 2 - 1 );

scene.add( mesh );

//parameter 2 - mass, parameter 3 - restitution ( how bouncy )
physics.addMesh( mesh, 1, 0.5 );

}

function onWindowResize( ) {

camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();

renderer.setSize( window.innerWidth, window.innerHeight );

}


function animate() {

if ( physicsHelper ) physicsHelper.update();

renderer.render( scene, camera );

stats.update();

}

</script>
</body>
</html>
Loading