• Stars
    star
    141
  • Rank 250,849 (Top 6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 2 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

👋💣 2d physics hooks for @react-three/fiber
yarn add @react-three/p2

React hooks for p2-es. Use this in combination with react-three-fiber.

  • Doesn't block the main thread, runs in a web worker
  • Supports instancing out of the box

TODOs

Shapes
  • useBox
  • useCapsule
  • useCircle
  • useConvex
  • useHeightfield
  • useLine
  • useParticle
  • usePlane
Raycast
  • useRaycastAny
  • useRaycastAll
  • useRaycastClosest

Springs

  • LinearSpring
  • RotationalSpring
  • Spring?

Constraints

  • DistanceConstraint
  • GearConstraint
  • LockConstraint
  • PrismaticConstraint
  • RevoluteConstraint

Other

  • useTopDownVehicle
  • useKinematicCharacterController
  • usePlatformController

Demos

Check out all of our examples at https://p2.pmnd.rs (coming soon)

Meanwhile look at the examples living in ./examples

How it works

  1. Get all the imports that you need.
import { Physics, useBox, ... } from '@react-three/p2'
  1. Create a physics world. normalIndex defines the rotation of the physics world in space. Use 1 for top-down and 2 for side-scroller like apps.
<Physics normalIndex={2}>{/* Physics related objects in here please */}</Physics>
  1. Pick a shape that suits your objects contact surface, it could be a box, plane, circle, etc. Give it a mass, too.
const [ref, api] = useBox(() => ({ mass: 1 }))
  1. Take your object, it could be a mesh, line, gltf, anything, and tie it to the reference you have just received. Et voilà, it will now be affected by gravity and other objects inside the physics world.
<mesh ref={ref} geometry={...} material={...} />
  1. You can interact with it by using the api, which lets you apply positions, rotations, velocities, forces and impulses.
useFrame(({ clock }) => api.position.set(Math.sin(clock.getElapsedTime()) * 5, 0))
  1. You can use the body api to subscribe to properties to get updates on each frame.
const velocity = useRef([0, 0])
useEffect(() => {
  const unsubscribe = api.velocity.subscribe((v) => (velocity.current = v))
  return unsubscribe
}, [])

Simple example

Let's make a ball falling onto a box.

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 (
    <mesh ref={ref}>
      <boxGeometry />
    </mesh>
  )
}

function Ball() {
  const [ref] = useCircle(() => ({ mass: 1, position: [0, 2] }))
  return (
    <mesh ref={ref}>
      <sphereGeometry />
    </mesh>
  )
}

ReactDOM.render(
  <Canvas>
    <Physics normalIndex={2}>
      <Box />
      <Ball />
    </Physics>
  </Canvas>,
  document.getElementById('root'),
)

Debug

You can debug your scene using the p2-es-debugger. This will show you how p2 "sees" your scene. Don't forget to tell both the same normalIndex.

import { Physics, Debug } from '@react-three/cannon'

ReactDOM.render(
  <Canvas>
    <Physics normalIndex={2}>
      <Debug color="black" scale={1.1} linewidth={0.01} normalIndex={2}>
        {/* children */}
      </Debug>
    </Physics>
  </Canvas>,
  document.getElementById('root'),
)

Api

Exports

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,
  // Maximum amount of physics objects inside your scene
  // Lower this value to save memory, increase if 1000 isn't enough
  size = 1000,
  solver = 'GS',
  stepSize = 1 / 60,
  tolerance = 0.001,
}: React.PropsWithChildren<ProviderProps>): JSX.Element

function Debug({ color = 'black', scale = 1 }: DebugProps): JSX.Element

function usePlane(
  fn: GetByIndex<PlaneProps>,
  fwdRef?: React.Ref<THREE.Object3D>,
  deps?: React.DependencyList,
): Api

function useBox(
  fn: GetByIndex<BoxProps>,
  fwdRef?: React.Ref<THREE.Object3D>,
  deps?: React.DependencyList,
): Api

function useCircle(
  fn: GetByIndex<CylinderProps>,
  fwdRef?: React.Ref<THREE.Object3D>,
  deps?: React.DependencyList,
): Api

function useTopDownVehicle(
  fn: () => RaycastVehicleProps,
  fwdRef?: React.Ref<THREE.Object3D>,
  deps: React.DependencyList[] = [],
): [React.RefObject<THREE.Object3D>, 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

Returned api

type WorkerApi = {
  [K in AtomicName]: AtomicApi<K>
} & {
  [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<THREE.Object3D>, PublicApi]

type AtomicName =
  | 'allowSleep'
  | 'angularDamping'
  | 'collisionGroup'
  | 'collisionMask'
  | 'collisionResponse'
  | 'fixedRotation'
  | 'isTrigger'
  | 'linearDamping'
  | 'mass'
  | 'material'
  | 'sleepSpeedLimit'
  | 'sleepTimeLimit'
  | 'userData'

type AtomicApi<K extends AtomicName> = {
  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
}

type ConstraintApi = [
  React.RefObject<THREE.Object3D>,
  React.RefObject<THREE.Object3D>,
  {
    enable: () => void
    disable: () => void
  },
]

type HingeConstraintApi = [
  React.RefObject<THREE.Object3D>,
  React.RefObject<THREE.Object3D>,
  {
    enable: () => void
    disable: () => void
    enableMotor: () => void
    disableMotor: () => void
    setMotorSpeed: (value: number) => void
    setMotorMaxForce: (value: number) => void
  },
]

type SpringApi = [
  React.RefObject<THREE.Object3D>,
  React.RefObject<THREE.Object3D>,
  {
    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
  }
}

Props

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
}

export type ProviderProps = InitProps & {
  isPaused?: boolean
  maxSubSteps?: number
  shouldInvalidate?: boolean
  size?: number
  stepSize?: number
}

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: {}
}

type Broadphase = 'Naive' | 'SAP'
type Triplet = [x: number, y: number, z: number]
type Quad = [x: number, y: number, z: number, w: number]

type VectorProps = Record<VectorName, Triplet>

type BodyProps<T extends any[] = unknown[]> = Partial<AtomicProps> &
  Partial<VectorProps> & {
    args?: T
    onCollide?: (e: CollideEvent) => void
    onCollideBegin?: (e: CollideBeginEvent) => void
    onCollideEnd?: (e: CollideEndEvent) => void
    quaternion?: Quad
    rotation?: Triplet
    type?: 'Dynamic' | 'Static' | 'Kinematic'
  }

type Event = RayhitEvent | CollideEvent | CollideBeginEvent | CollideEndEvent
type CollideEvent = {
  op: string
  type: 'collide'
  body: THREE.Object3D
  target: THREE.Object3D
  contact: {
    // the world position of the point of contact
    contactPoint: number[]
    // the normal of the collision on the surface of
    // the colliding body
    contactNormal: number[]
    // velocity of impact along the contact normal
    impactVelocity: number
    // a unique ID for each contact event
    id: string
    // these are lower-level properties from cannon:
    // bi: one of the bodies involved in contact
    bi: THREE.Object3D
    // bj: the other body involved in contact
    bj: THREE.Object3D
    // ni: normal of contact relative to bi
    ni: number[]
    // ri: the point of contact relative to bi
    ri: number[]
    // rj: the point of contact relative to bj
    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
}

type CylinderArgs = [radiusTop?: number, radiusBottom?: number, height?: number, numSegments?: number]
type SphereArgs = [radius: number]
type TrimeshArgs = [vertices: ArrayLike<number>, indices: ArrayLike<number>]
type HeightfieldArgs = [
  data: number[][],
  options: { elementSize?: number; maxValue?: number; minValue?: number },
]
type ConvexPolyhedronArgs<V extends VectorTypes = VectorTypes> = [
  vertices?: V[],
  faces?: number[][],
  normals?: V[],
  axes?: V[],
  boundingSphereRadius?: number,
]

interface PlaneProps extends BodyProps {}
interface BoxProps extends BodyProps<Triplet> {} // extents: [x, y, z]
interface CylinderProps extends BodyProps<CylinderArgs> {}
interface ParticleProps extends BodyProps {}
interface SphereProps extends BodyProps<SphereArgs> {}
interface TrimeshProps extends BodyPropsArgsRequired<TrimeshArgs> {}
interface HeightfieldProps extends BodyPropsArgsRequired<HeightfieldArgs> {}
interface ConvexPolyhedronProps extends BodyProps<ConvexPolyhedronArgs> {}
interface CompoundBodyProps extends BodyProps {
  shapes: BodyProps & { type: ShapeType }[]
}

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 {}

interface SpringOptns {
  restLength?: number
  stiffness?: number
  damping?: number
  worldAnchorA?: Triplet
  worldAnchorB?: Triplet
  localAnchorA?: Triplet
  localAnchorB?: Triplet
}

interface WheelInfoOptions {
  radius?: number
  directionLocal?: Triplet
  suspensionStiffness?: number
  suspensionRestLength?: number
  maxSuspensionForce?: number
  maxSuspensionTravel?: number
  dampingRelaxation?: number
  dampingCompression?: number
  frictionSlip?: number
  rollInfluence?: number
  axleLocal?: Triplet
  chassisConnectionPointLocal?: Triplet
  isFrontWheel?: boolean
  useCustomSlidingRotationalSpeed?: boolean
  customSlidingRotationalSpeed?: number
}

interface RaycastVehicleProps {
  chassisBody: React.Ref<THREE.Object3D>
  wheels: React.Ref<THREE.Object3D>[]
  wheelInfos: WheelInfoOptions[]
  indexForwardAxis?: number
  indexRightAxis?: number
  indexUpAxis?: number
}

FAQ

Broadphases

  • NaiveBroadphase is as simple as it gets. It considers every body to be a potential collider with every other body. This results in the maximum number of narrowphase checks.
  • SAPBroadphase sorts bodies along an axis and then moves down that list finding pairs by looking at body size and position of the next bodies. Control what axis to sort along by setting the axisIndex property.

Types

  • A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass.
  • A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies.
  • A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies.

More Repositories

1

zustand

🐻 Bear necessities for state management in React
TypeScript
40,808
star
2

react-spring

✌️ A spring physics based React animation library
TypeScript
27,160
star
3

react-three-fiber

🇨🇭 A React renderer for Three.js
TypeScript
25,320
star
4

jotai

👻 Primitive and flexible state management for React
TypeScript
16,893
star
5

use-gesture

👇Bread n butter utility for component-tied mouse/touch gestures in React and Vanilla Javascript.
TypeScript
8,537
star
6

valtio

💊 Valtio makes proxy-state simple for React and Vanilla
TypeScript
8,257
star
7

drei

🥉 useful helpers for react-three-fiber
JavaScript
7,122
star
8

leva

🌋 React-first components GUI
TypeScript
4,528
star
9

gltfjsx

🎮 Turns GLTFs into JSX components
JavaScript
3,949
star
10

use-cannon

👋💣 physics based hooks for @react-three/fiber
TypeScript
2,654
star
11

react-three-next

React Three Fiber, Threejs, Nextjs starter
JavaScript
2,140
star
12

postprocessing

A post processing library for three.js.
JavaScript
2,100
star
13

racing-game

🏎 Open source racing game developed by everyone willing
TypeScript
2,094
star
14

react-xr

🤳 VR/AR with react-three-fiber
TypeScript
1,890
star
15

react-three-flex

💪📦 Flexbox for react-three-fiber
TypeScript
1,606
star
16

suspend-react

🚥 Async/await for React components
TypeScript
1,308
star
17

react-postprocessing

📬 postprocessing for react-three-fiber
JavaScript
1,009
star
18

detect-gpu

Classifies GPUs based on their 3D rendering benchmark score allowing the developer to provide sensible default settings for graphically intensive applications.
TypeScript
979
star
19

lamina

🍰 An extensible, layer based shader material for ThreeJS
TypeScript
976
star
20

its-fine

🐶🔥 A collection of escape hatches for React.
TypeScript
891
star
21

react-use-measure

🙌 Utility to measure view bounds
TypeScript
799
star
22

react-nil

⃝ A react null renderer
TypeScript
772
star
23

react-three-rapier

🤺 Rapier physics in React
TypeScript
765
star
24

maath

🪶 Math helpers for the rest of us
TypeScript
755
star
25

threejs-journey

⚛️ Bruno Simons journey demos in React
TypeScript
685
star
26

three-stdlib

📚 Stand-alone library of threejs examples designed to run without transpilation in node & browser
JavaScript
624
star
27

react-three-editor

🔌 A one of a kind scene editor that writes changes back into your code
TypeScript
602
star
28

react-three-a11y

♿️ Accessibility tools for React Three Fiber
TypeScript
507
star
29

react-zdog

⚡️🐶 React bindings for zdog
JavaScript
441
star
30

use-asset

📦 A promise caching strategy for React Suspense
TypeScript
414
star
31

react-three-offscreen

📺 Offscreen worker canvas for react-three-fiber
TypeScript
397
star
32

drei-vanilla

🍦 drei-inspired helpers for threejs
TypeScript
364
star
33

ecctrl

🕹️ A floating rigibody character controller
TypeScript
349
star
34

tunnel-rat

🐀 Non gratum anus rodentum
TypeScript
287
star
35

react-three-lgl

🔆 A React abstraction for the LGL Raycaster
TypeScript
260
star
36

market

📦 Download CC0 assets ready to use in your next 3D Project
JavaScript
249
star
37

react-three-csg

🚧 Constructive solid geometry for React
TypeScript
242
star
38

gltf-react-three

Convert GLTF files to React Three Fiber Components
JavaScript
230
star
39

component-material

🧩 Compose modular materials in React
TypeScript
161
star
40

env

💄 An app to create, edit, and preview HDR environment maps in the browser
TypeScript
143
star
41

react-ogl

🦴 A barebones react renderer for ogl.
TypeScript
139
star
42

react-spring-examples

JavaScript
138
star
43

react-three-gpu-pathtracer

⚡️ A React abstraction for the popular three-gpu-pathtracer
TypeScript
125
star
44

react-three-lightmap

In-browser lightmap/AO baker for react-three-fiber and ThreeJS
TypeScript
123
star
45

cannon-es-debugger

Wireframe debugger for use with cannon-es https://github.com/react-spring/cannon-es
HTML
103
star
46

rafz

💍 One loop to frame them all.
TypeScript
96
star
47

website

Poimandres developer collective website
JavaScript
87
star
48

swc-jotai

Rust
85
star
49

assets

📦 Importable base64 encoded CC0 assets
Makefile
84
star
50

react-three-scissor

✂ Multiple scenes, one canvas! WebGL Scissoring implementation for React Three Fiber.
TypeScript
81
star
51

eslint-plugin-valtio

An eslint plugin for better valtio experience
JavaScript
69
star
52

react-spring.io

✌️ A spring physics based React animation library
TypeScript
56
star
53

react-three-babel

🛍 A Babel plugin that automatically builds the extend catalogue of known native Three.js elements
TypeScript
53
star
54

r3f-website

Website for React Three Fiber
JavaScript
26
star
55

market-assets

JavaScript
19
star
56

react-three-8thwall

JavaScript
17
star
57

drei-assets

JavaScript
16
star
58

discord

🤖 Poimandres Discord Bot
TypeScript
10
star
59

react-three-jolt

⚡ Jolt physics in React
CSS
10
star
60

branding

TypeScript
7
star
61

market-assets-do

JavaScript
5
star
62

envinfo

Easily collect useful information for bug reports
JavaScript
4
star
63

leva-wg

1
star