Description
I need to dynamically change the mass of a cube (dynamic RigidBody) gliding on a tilted floor (fixed RigidBody). I explicitely create the cube with a mass and use setAdditionalMass() method to update the mass through a leva control.
The issue is that the mass variations don't affect the animation of the cube physics, although the RigidBody reference seems to be correctly updated with my new mass values.
Here's my full code snippet:
import { Box } from "@react-three/drei";
import { useFrame } from "@react-three/fiber";
import { Physics, RapierRigidBody, RigidBody } from "@react-three/rapier";
import { useControls } from "leva";
import React, { useEffect, useRef } from "react";
const Floor = () => {
const floorRef = useRef<RapierRigidBody>(null);
const { friction } = useControls({
friction: { value: 0, min: 0, max: 1, step: 0.01 },
});
useFrame(() => {
// if (floorRef.current) {
// console.log("Current floor friction:", floorRef.current.friction());
// }
});
return (
<RigidBody
ref={floorRef}
type="fixed"
colliders="cuboid"
name="floor"
friction={friction}
>
<Box
position={[0, -5, 0]}
scale={[50, 2, 250]}
rotation={[Math.PI / 20, 0, 0]} // Tilt the floor
receiveShadow
>
<meshStandardMaterial color={"lightgray"} />
</Box>
</RigidBody>
);
};
const Cube = () => {
const cubeRef = useRef<RapierRigidBody>(null);
const { mass } = useControls({
mass: { value: 30, min: 30, max: 100000, step: 1 },
});
useEffect(() => {
if (cubeRef.current) {
// Set the new mass when it changes
cubeRef.current.setAdditionalMass(mass, true);
}
}, [mass]);
useFrame(() => {
if (cubeRef.current) {
console.log("Current cube mass:", cubeRef.current.mass());
}
});
const size = 3;
return (
<RigidBody
ref={cubeRef}
colliders="cuboid"
mass={mass} // Initial mass
position={[0, 40, -100]}
friction={0}
// ccd={true}
>
<Box scale={[size, size, size]} castShadow receiveShadow name="cube">
<meshStandardMaterial color={"lightgreen"} />
</Box>
</RigidBody>
);
};
export const CubeMassGliding: React.FC = () => {
return (
<Physics gravity={[0, -9.81, 0]} debug>
<group>
<Cube />
<Floor />
</group>
<axesHelper />
</Physics>
);
};
The expectation is for seeing an acceleration of the cube gliding while increasing its mass, and a deceleration while decreasing it.
I am looking for insights into why this might be happening and how to resolve it, because I couldn't find any demo about mass handling in the github repo. Is there a specific configuration that I am missing, or could this be a potential bug in the library ? Any help or guidance would be greatly appreciated.
Thank you!