usePhysics
The usePhysics hook provides information on the physics engine state. It allows you to check if physics is enabled, loaded, and to handle any physics-related errors.
PlayCanvas React lazily loads and instantiates the physics engine allowing you to render content ahead of time. The usePhysics provides a reactive mechanism to check the physics engine state.
You can read more about the physics system in the Physics guide or the Rigidbody and Collision components.
Usage
Conditional Rendering
import { usePhysics } from '@playcanvas/react/hooks'
function PhysicsInfo() {
const { isPhysicsEnabled, isPhysicsLoaded, physicsError } = usePhysics()
if (!isPhysicsLoaded) return null
return (<Entity>
<Rigidbody type="box" />
<Collision type="box" />
<Render type="box" />
</Entity>)
}
Safe Physics Component Creation
import { usePhysics } from '@playcanvas/react/hooks'
function SafePhysicsEntity() {
const { isPhysicsEnabled, isPhysicsLoaded } = usePhysics()
return (
<Entity>
<Render type="box" />
{isPhysicsEnabled && isPhysicsLoaded && (
<>
<Collision type="box" />
<Rigidbody type="dynamic" mass={5} />
</>
)}
</Entity>
)
}
Physics with Fallback
import { usePhysics } from '@playcanvas/react/hooks'
function PhysicsWithFallback() {
const { isPhysicsEnabled, isPhysicsLoaded } = usePhysics()
if (isPhysicsEnabled && isPhysicsLoaded) {
return (
<Entity>
<Collision type="box" />
<Rigidbody type="dynamic" mass={10} />
<Render type="box" />
</Entity>
)
}
// Fallback without physics
return (
<Entity>
<Render type="box" />
</Entity>
)
}
Properties
| Name | Type | Default |
|---|---|---|
isPhysicsEnabled | booleanWhether physics is enabled on the application. | - |
isPhysicsLoaded | booleanWhether the physics library has been successfully loaded. | - |
physicsError | Error | nullThe error that occurred when loading physics, if any. | - |
Related
- useApp - Access the Application instance
- Collision Component - Create collision components
- Rigidbody Component - Create rigidbody components
- Application Component - Enable physics with usePhysics prop