### Start Development Server
Source: https://github.com/pmndrs/use-p2/blob/main/examples/readme.md
Command to start the development server for the examples and the URL to access the application.
```bash
npm run dev
# Visit http://localhost:3000 in your browser
```
--------------------------------
### Build and Run Parent Project
Source: https://github.com/pmndrs/use-p2/blob/main/examples/readme.md
Commands to build the parent project and install dependencies for the examples directory.
```bash
cd ..
yarn
npm run build
cd examples
yarn
```
--------------------------------
### Basic Physics Setup
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Demonstrates the fundamental setup for integrating the Physics component from @react-three/p2 into a react-three-fiber canvas. It shows how to import necessary components and configure the physics world with a `normalIndex`.
```jsx
import { Canvas } from '@react-three/fiber'
import { Physics, useBox, useCircle } from '@react-three/p2'
function Box() {
const [ref] = useBox(() => ({ mass: 0, position: [0, -2] }))
return (
)
}
function Ball() {
const [ref] = useCircle(() => ({ mass: 1, position: [0, 2] }))
return (
)
}
ReactDOM.render(
,
document.getElementById('root'),
)
```
--------------------------------
### Debugging Physics Scene
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Provides an example of how to use the `p2-es-debugger` to visualize the physics simulation within the scene. It requires importing the `Debug` component and ensuring consistent `normalIndex` values between `Physics` and `Debug`.
```jsx
import { Physics, Debug } from '@react-three/cannon'
ReactDOM.render(
,
document.getElementById('root'),
)
```
--------------------------------
### Physics Initialization Properties
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Defines the properties for initializing the physics engine. Includes options for gravity, iterations, broadphase, and contact material.
```typescript
type InitProps = {
allowSleep?: boolean
axisIndex?: number
broadphase?: Broadphase
defaultContactMaterial?: {
friction?: number
restitution?: number
contactEquationStiffness?: number
contactEquationRelaxation?: number
frictionEquationStiffness?: number
frictionEquationRelaxation?: number
}
gravity?: Duplet
iterations?: number
normalIndex?: number
quatNormalizeFast?: boolean
quatNormalizeSkip?: number
solver?: Solver
tolerance?: number
}
type Broadphase = 'Naive' | 'SAP'
```
--------------------------------
### Spring Options
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Defines the options for configuring physics springs, including rest length, stiffness, and anchors.
```typescript
interface SpringOptns {
restLength?: number
stiffness?: number
damping?: number
worldAnchorA?: Triplet
worldAnchorB?: Triplet
localAnchorA?: Triplet
localAnchorB?: Triplet
}
```
--------------------------------
### Using Physics Shapes
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Shows how to use a physics shape, specifically `useBox`, to define an object's contact surface and its physical properties like mass. The returned `ref` is then used to tie the object to the physics simulation.
```jsx
const [ref, api] = useBox(() => ({ mass: 1 }))
```
--------------------------------
### Physics Provider and Debug Component
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Defines the main Physics provider component for setting up the physics world and the Debug component for visualizing physics objects.
```typescript
function Physics({
allowSleep = false,
axisIndex = 0,
normalIndex = 0,
broadphase = 'Naive',
children,
defaultContactMaterial = { contactEquationStiffness: 1e6 },
gravity = [0, -9.81, 0],
isPaused = false,
iterations = 5,
maxSubSteps = 10,
quatNormalizeFast = false,
quatNormalizeSkip = 0,
shouldInvalidate = true,
size = 1000,
solver = 'GS',
stepSize = 1 / 60,
tolerance = 0.001,
}: React.PropsWithChildren): JSX.Element
function Debug({ color = 'black', scale = 1 }: DebugProps): JSX.Element
```
--------------------------------
### Physics World Configuration
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Illustrates how to create a physics world using the `Physics` component. The `normalIndex` prop is crucial for defining the physics world's orientation, with `1` for top-down and `2` for side-scroller applications.
```jsx
{/* Physics related objects in here please */}
```
--------------------------------
### Broadphase Collision Detection Algorithms
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Explains different broadphase collision detection algorithms used in physics engines. NaiveBroadphase checks all body pairs, while SAPBroadphase uses a sweep-and-prune approach for efficiency.
```APIDOC
Broadphases:
NaiveBroadphase:
Description: Checks every body against every other body for potential collisions. This method results in the maximum number of narrowphase checks.
Usage: Suitable for scenes with a very small number of bodies.
SAPBroadphase:
Description: Sorts bodies along a specified axis and then iterates through the sorted list, checking for collisions based on body size and position. The axis for sorting can be controlled by the 'axisIndex' property.
Parameters:
axisIndex: The index of the axis (0 for x, 1 for y, 2 for z) to sort bodies along.
Usage: More efficient than NaiveBroadphase for scenes with a moderate to large number of bodies.
```
--------------------------------
### Constraint and Vehicle API Definitions
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Defines the APIs for various physics constraints (hinge, generic) and the specific API for the RaycastVehicle.
```typescript
type ConstraintApi = [
React.RefObject,
React.RefObject,
{
enable: () => void
disable: () => void
},
]
type HingeConstraintApi = [
React.RefObject,
React.RefObject,
{
enable: () => void
disable: () => void
enableMotor: () => void
disableMotor: () => void
setMotorSpeed: (value: number) => void
setMotorMaxForce: (value: number) => void
},
]
type SpringApi = [
React.RefObject,
React.RefObject,
{
setStiffness: (value: number) => void
setRestLength: (value: number) => void
setDamping: (value: number) => void
},
]
interface RaycastVehiclePublicApi {
applyEngineForce: (value: number, wheelIndex: number) => void
setBrake: (brake: number, wheelIndex: number) => void
setSteeringValue: (value: number, wheelIndex: number) => void
sliding: {
subscribe: (callback: (sliding: boolean) => void) => void
}
}
```
--------------------------------
### Constraint Options
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Defines common options for physics constraints, such as maximum force and collision settings.
```typescript
interface ConstraintOptns {
maxForce?: number
collideConnected?: boolean
wakeUpBodies?: boolean
}
interface PointToPointConstraintOpts extends ConstraintOptns {
pivotA: Triplet
pivotB: Triplet
}
interface ConeTwistConstraintOpts extends ConstraintOptns {
pivotA?: Triplet
axisA?: Triplet
pivotB?: Triplet
axisB?: Triplet
angle?: number
twistAngle?: number
}
interface DistanceConstraintOpts extends ConstraintOptns {
distance?: number
}
interface HingeConstraintOpts extends ConstraintOptns {
pivotA?: Triplet
axisA?: Triplet
pivotB?: Triplet
axisB?: Triplet
}
interface LockConstraintOpts extends ConstraintOptns {}
```
--------------------------------
### Subscribing to Body Properties
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Demonstrates how to subscribe to changes in a physics body's properties, such as velocity, using the `api` object. This allows for real-time updates and reactions to physics simulations within the React component lifecycle.
```javascript
const velocity = useRef([0, 0])
useEffect(() => {
const unsubscribe = api.velocity.subscribe((v) => (velocity.current = v))
return unsubscribe
}, [])
```
--------------------------------
### Vehicle and Raycasting Hooks
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Includes hooks for simulating vehicles and performing raycasts for collision detection.
```typescript
function useTopDownVehicle(
fn: () => RaycastVehicleProps,
fwdRef?: React.Ref,
deps: React.DependencyList[] = [],
): [React.RefObject, RaycastVehiclePublicApi]
function useRaycastClosest(
options: RayOptions,
callback: (e: RayhitEvent) => void,
deps: React.DependencyList = [],
): void
function useRaycastAny(
options: RayOptions,
callback: (e: RayhitEvent) => void,
deps: React.DependencyList = [],
): void
function useRaycastAll(
options: RayOptions,
callback: (e: RayhitEvent) => void,
deps: React.DependencyList = [],
): void
```
--------------------------------
### Raycast Vehicle Properties
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Specifies the properties required for setting up a raycast vehicle, including references to the chassis and wheels, and an array of wheel information.
```typescript
interface RaycastVehicleProps {
chassisBody: React.Ref
wheels: React.Ref[]
wheelInfos: WheelInfoOptions[]
indexForwardAxis?: number
indexRightAxis?: number
indexUpAxis?: number
}
```
--------------------------------
### Physics Provider Properties
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Extends initialization properties with options specific to the provider component, such as pausing, step size, and invalidation.
```typescript
export type ProviderProps = InitProps & {
isPaused?: boolean
maxSubSteps?: number
shouldInvalidate?: boolean
size?: number
stepSize?: number
}
```
--------------------------------
### Vehicle Wheel Info Properties
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Defines the properties for configuring a vehicle's wheel suspension and behavior. Includes parameters for suspension travel, damping, friction, and wheel orientation.
```typescript
interface WheelInfoOptions {
maxSuspensionTravel?: number
dampingRelaxation?: number
dampingCompression?: number
frictionSlip?: number
rollInfluence?: number
axleLocal?: Triplet
chassisConnectionPointLocal?: Triplet
isFrontWheel?: boolean
useCustomSlidingRotationalSpeed?: boolean
customSlidingRotationalSpeed?: number
}
```
--------------------------------
### Interacting with Physics Bodies
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Explains how to interact with physics bodies using the `api` object returned by physics hooks. This API allows for manipulating an object's position, rotation, velocity, forces, and impulses.
```jsx
useFrame(({ clock }) => api.position.set(Math.sin(clock.getElapsedTime()) * 5, 0))
```
--------------------------------
### Wheel Information Options
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Specifies options for wheel information in vehicle physics, such as radius and suspension properties.
```typescript
interface WheelInfoOptions {
radius?: number
directionLocal?: Triplet
suspensionStiffness?: number
suspensionRestLength?: number
maxSuspensionForce?: number
}
```
--------------------------------
### Physics Event Types
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Defines the structure for various physics events, including collision details, begin/end collisions, and ray hits.
```typescript
type Event = RayhitEvent | CollideEvent | CollideBeginEvent | CollideEndEvent
type CollideEvent = {
op: string
type: 'collide'
body: THREE.Object3D
target: THREE.Object3D
contact: {
contactPoint: number[]
contactNormal: number[]
impactVelocity: number
id: string
bi: THREE.Object3D
bj: THREE.Object3D
ni: number[]
ri: number[]
rj: number[]
}
collisionFilters: {
bodyFilterGroup: number
bodyFilterMask: number
targetFilterGroup: number
targetFilterMask: number
}
}
type CollideBeginEvent = {
op: 'event'
type: 'collideBegin'
target: Object3D
body: Object3D
}
type CollideEndEvent = {
op: 'event'
type: 'collideEnd'
target: Object3D
body: Object3D
}
type RayhitEvent = {
op: string
type: 'rayhit'
body: THREE.Object3D
target: THREE.Object3D
}
```
--------------------------------
### Physics Shape Hooks
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Provides hooks for creating and managing different physics shapes like planes, boxes, and circles within the physics world.
```typescript
function usePlane(
fn: GetByIndex,
fwdRef?: React.Ref,
deps?: React.DependencyList,
): Api
function useBox(
fn: GetByIndex,
fwdRef?: React.Ref,
deps?: React.DependencyList,
): Api
function useCircle(
fn: GetByIndex,
fwdRef?: React.Ref,
deps?: React.DependencyList,
): Api
```
--------------------------------
### Worker API and Public API Interfaces
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Defines the interfaces for interacting with the physics worker and the public API exposed to the application.
```typescript
type WorkerApi = {
[K in AtomicName]: AtomicApi
} & {
[K in VectorName]: VectorApi
} & {
applyForce: (force: Triplet, worldPoint: Triplet) => void
applyImpulse: (impulse: Triplet, worldPoint: Triplet) => void
applyLocalForce: (force: Triplet, localPoint: Triplet) => void
applyLocalImpulse: (impulse: Triplet, localPoint: Triplet) => void
applyTorque: (torque: Triplet) => void
quaternion: QuaternionApi
rotation: VectorApi
sleep: () => void
wakeUp: () => void
}
interface PublicApi extends WorkerApi {
at: (index: number) => WorkerApi
}
type Api = [React.RefObject, PublicApi]
```
--------------------------------
### Physics Body Types
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Defines the different types of bodies in a physics simulation and their behavior regarding movement, mass, and collisions.
```APIDOC
Body Types:
Dynamic Body:
Description: A body that is fully simulated and moves according to applied forces. It can be manually moved but typically responds to physics. Dynamic bodies have finite, non-zero mass and can collide with all other body types.
Static Body:
Description: A body that does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting their position, but their velocity is always zero. They do not collide with other static or kinematic bodies.
Kinematic Body:
Description: A body that moves according to its velocity during simulation and does not respond to forces. Kinematic bodies behave as if they have infinite mass and are typically moved by directly setting their velocity. They do not collide with other static or kinematic bodies.
```
--------------------------------
### Atomic and Vector API Definitions
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Details the specific APIs for accessing and modifying atomic properties (like mass, damping) and vector properties (like velocity, position) of physics objects.
```typescript
type AtomicName =
| 'allowSleep'
| 'angularDamping'
| 'collisionGroup'
| 'collisionMask'
| 'collisionResponse'
| 'fixedRotation'
| 'isTrigger'
| 'linearDamping'
| 'mass'
| 'material'
| 'sleepSpeedLimit'
| 'sleepTimeLimit'
| 'userData'
type AtomicApi = {
set: (value: AtomicProps[K]) => void
subscribe: (callback: (value: AtomicProps[K]) => void) => () => void
}
type QuaternionApi = {
set: (x: number, y: number, z: number, w: number) => void
copy: ({ w, x, y, z }: Quaternion) => void
subscribe: (callback: (value: Quad) => void) => () => void
}
type VectorName = 'angularFactor' | 'angularVelocity' | 'linearFactor' | 'position' | 'velocity'
type VectorApi = {
set: (x: number, y: number, z: number) => void
copy: ({ x, y, z }: Vector3 | Euler) => void
subscribe: (callback: (value: Triplet) => void) => () => void
}
```
--------------------------------
### Shape Arguments Definitions
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Specifies the argument types for various physics shapes like cylinders, spheres, and meshes.
```typescript
type CylinderArgs = [radiusTop?: number, radiusBottom?: number, height?: number, numSegments?: number]
type SphereArgs = [radius: number]
type TrimeshArgs = [vertices: ArrayLike, indices: ArrayLike]
type HeightfieldArgs = [
data: number[][],
options: { elementSize?: number; maxValue?: number; minValue?: number },
]
type ConvexPolyhedronArgs = [
vertices?: V[],
faces?: number[][],
normals?: V[],
axes?: V[],
boundingSphereRadius?: number,
]
```
--------------------------------
### Atomic Body Properties
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Defines the fundamental atomic properties of a physics body, including damping, collision filters, mass, and material.
```typescript
type AtomicProps = {
allowSleep: boolean
angularDamping: number
collisionFilterGroup: number
collisionFilterMask: number
collisionResponse: number
fixedRotation: boolean
isTrigger: boolean
linearDamping: number
mass: number
material: MaterialOptions
sleepSpeedLimit: number
sleepTimeLimit: number
userData: {}
}
```
--------------------------------
### Vector and Body Properties
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Defines properties related to vectors (like position and rotation) and general body properties, including event handlers.
```typescript
type Triplet = [x: number, y: number, z: number]
type Quad = [x: number, y: number, z: number, w: number]
type VectorProps = Record
type BodyProps = Partial &
Partial &
{
args?: T
onCollide?: (e: CollideEvent) => void
onCollideBegin?: (e: CollideBeginEvent) => void
onCollideEnd?: (e: CollideEndEvent) => void
quaternion?: Quad
rotation?: Triplet
type?: 'Dynamic' | 'Static' | 'Kinematic'
}
```
--------------------------------
### Specific Body Type Props
Source: https://github.com/pmndrs/use-p2/blob/main/README.md
Defines the props for specific physics body types, including Plane, Box, Cylinder, Sphere, Trimesh, Heightfield, ConvexPolyhedron, and CompoundBody.
```typescript
interface PlaneProps extends BodyProps {}
interface BoxProps extends BodyProps {} // extents: [x, y, z]
interface CylinderProps extends BodyProps {}
interface ParticleProps extends BodyProps {}
interface SphereProps extends BodyProps {}
interface TrimeshProps extends BodyPropsArgsRequired {}
interface HeightfieldProps extends BodyPropsArgsRequired {}
interface ConvexPolyhedronProps extends BodyProps {}
interface CompoundBodyProps extends BodyProps {
shapes: BodyProps & { type: ShapeType }[]
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.