BVHEcctrl

A simple R3f character controller

入门
GitHub在线演示
Stars:119
License:MIT License
更新:2025/12/18

README

🕹️ BVHEcctrl

Demo Preview

BVHEcctrl is a lightweight, plug-and-play character controller designed for react-three-fiber. It requires no physics engine, and utilizes three-mesh-bvh for highly efficient, triangle-accurate collision detection and response.

🧠 Ideal for web-based 3D experiences such as games, interactive portfolios, and virtual worlds.


📸 Examples

Demo 1 Demo 2


✨ Features

  • No physics engine required
  • Fast BVH-based collision detection
  • Smooth floating capsule movement for stairs, slopes, and uneven surfaces
  • Built-in support for:
    • StaticCollider
    • KinematicCollider
    • InstancedStaticCollider

📦 Installation

npm install bvhecctrl

⚙️ How to Use

Step 1: Setup Keyboard Controls and Character Controller

import BVHEcctrl from "bvhecctrl";
import { KeyboardControls } from "@react-three/drei";

const keyboardMap = [
  { name: "forward", keys: ["ArrowUp", "KeyW"] },
  { name: "backward", keys: ["ArrowDown", "KeyS"] },
  { name: "leftward", keys: ["ArrowLeft", "KeyA"] },
  { name: "rightward", keys: ["ArrowRight", "KeyD"] },
  { name: "jump", keys: ["Space"] },
  { name: "run", keys: ["Shift"] },
];

return (
  <KeyboardControls map={keyboardMap}>
    <BVHEcctrl ref={ecctrlRef}>
      <CharacterModel />
    </BVHEcctrl>
  </KeyboardControls>
);

Step 2: Add Colliders to Your Map

import {
  StaticCollider,
  KinematicCollider,
  InstancedStaticCollider,
} from "bvhecctrl";

useFrame((_, delta) => {
  if (kinematicRef.current) kinematicRef.current.rotation.y += delta;
});

return (
  <>
    <StaticCollider>
      <MapModel />
    </StaticCollider>

    <KinematicCollider ref={kinematicRef}>
      <MapModel />
    </KinematicCollider>

    <InstancedStaticCollider>
      <InstancedMapModel />
    </InstancedStaticCollider>
  </>
);

Step 3: Handle Camera Movement

You can use any camera control system that fits your needs — such as <OrbitControls>, <PointerLockControls>, <CameraControls>, or your own custom setup. For smooth and flexible control, I highly recommend using <CameraControls> from @react-three/drei. It even offers built-in camera collision support.

Here’s a simple example using <CameraControls> to follow the character:

useFrame(() => {
  camControlRef.current.moveTo(
    ecctrlRef.current.group.position.x,
    ecctrlRef.current.group.position.y + 0.3,
    ecctrlRef.current.group.position.z,
    true
  );
});

🧱 BVHEcctrl Props

PropTypeDefaultDescription
debugbooleanfalseEnables visual debugging.
colliderCapsuleArgs[number, number, number, number][0.3, 0.6, 4, 8]Capsule shape: [radius, height, capSegments, radialSegments].
pausedbooleanfalseFreezes character physics and collision response.
delaynumber1.5Physics delay after initialization (in seconds).
gravitynumber9.81World gravity.
fallGravityFactornumber4Multiplier to increase falling speed.
maxFallSpeednumber50Maximum fall velocity cap.
massnumber1Virtual mass, affects float behavior.
sleepTimeoutnumber10Time before character enters sleep state when idle.
slowMotionFactornumber1Global time scaling (e.g., 0.5 = half-speed).
turnSpeednumber15Turn speed when changing direction.
maxWalkSpeednumber3Max speed when walking.
maxRunSpeednumber5Max speed when running.
accelerationnumber30Speed increase per second.
decelerationnumber20Speed decrease when input is released.
counterAccFactornumber0.5Extra acceleration multiplier when changing direction.
airDragFactornumber0.3Simulated drag while in air.
jumpVelnumber5Upward velocity when jumping.
floatCheckType"RAYCAST" | "SHAPECAST" | "BOTH"BOTHAble to switch between different float check type.
maxSlopenumber1Max walkable surface slope (in radians).
floatHeightnumber0.2Desired float height above ground.
floatPullBackHeightnumber0.25Additional distance below ground used to pull character down.
floatSensorRadiusnumber0.12Radius of the sensor used to sense the ground.
floatSpringKnumber600Spring constant for floating.
floatDampingCnumber28Damping factor for float spring (prevents oscillation).
collisionCheckIterationnumber3Number of collision check per frame.
collisionPushBackVelocitynumber3Extra velocity applied to resolve penetration.
collisionPushBackDampingnumber0.1Damping applied to the pushback force.
collisionPushBackThresholdnumber0.005Minimum depth before pushback activates.

🧱 Collider Component Props

PropTypeDefaultDescription
debugbooleanfalseShows BVH bounds for debugging.
debugVisualizeDepthnumber10Depth level of BVH to visualize (debug only).
restitutionnumber0.05Bounciness on impact.
frictionnumber0.8Surface friction against character movement.
excludeFloatHitbooleanfalseIf true, this collider is ignored in float sensor checks.
excludeCollisionCheckbooleanfalseIf true, this collider is excluded from collision detection.
BVHOptionsobject(see below)Configuration for building the internal BVH tree.

Default BVHOptions:

{
  strategy: SAH,
  verbose: false,
  setBoundingBox: true,
  maxDepth: 40,
  maxLeafTris: 10,
  indirect: false
}

🎮 Virtual Joystick and Button Integration

BVHEcctrl provides mobile-friendly UI components to control character movement and actions using touch input. Simply import and place <Joystick /> and <VirtualButton /> outside the <Canvas> component:

import { Joystick, VirtualButton } from "bvhecctrl";

<Joystick />

<VirtualButton
  id="run"
  label="RUN"
  buttonWrapperStyle={{ right: "100px", bottom: "40px" }}
/>

<VirtualButton
  id="jump"
  label="JUMP"
  buttonWrapperStyle={{ right: "40px", bottom: "100px" }}
/>

You can define additional components beyond the built-in "run" and "jump" ones, such as:

import { VirtualButton, useButtonStore } from "bvhecctrl";

<VirtualButton id="dance" />;

// Later access it in your logic
const { buttons } = useButtonStore.getState();
console.log(buttons.dance); // true or false

🧱 Joystick Component Props

PropTypeDefaultDescription
joystickMaxRadiusnumber50Maximum drag radius.
joystickWrapperStyleReact.CSSProperties-CSS style for the outer wrapper.
joystickBaseStyleReact.CSSProperties-CSS style for the joystick base.
joystickKnobStyleReact.CSSProperties-CSS style for the draggable knob.

🧱 VirtualButton Component Props

PropTypeDefaultDescription
idstring-Unique ID to map to actions ("run" & "jump" are handled).
labelstring-Optional label text on the button.
buttonWrapperStyleReact.CSSProperties-CSS style for the wrapper container.
buttonCapStyleReact.CSSProperties-CSS style for the button cap.

🧩 Extra Utilities

Accessing the Controller Ref:

// Access the character group (THREE.Group)
ecctrlRef.current.group;

// Access the character model (THREE.Group)
ecctrlRef.current.model;

// Reset current velocity to zero
ecctrlRef.current.resetLinVel();

// Add linear velocity directly
ecctrlRef.current.addLinVel(THREE.Vector3);

// Set linear velocity directly
ecctrlRef.current.setLinVel(THREE.Vector3);

// Set character movement, can have one or more inputs
ecctrlRef.current.setMovement({
  forward: boolean,
  backward: boolean,
  leftward: boolean,
  rightward: boolean,
  joystick: { x: number; y: number },
  run: boolean,
  jump: boolean,
});

Read-only Character Status:

import { characterStatus } from "bvhecctrl";

characterStatus.position; // THREE.Vector3
characterStatus.linvel; // THREE.Vector3
characterStatus.quaternion; // THREE.Quaternion
characterStatus.inputDir; // THREE.Vector3
characterStatus.movingDir; // THREE.Vector3
characterStatus.isOnGround; // boolean
characterStatus.isOnMovingPlatform; // boolean
characterStatus.animationStatus; // "IDLE" | "WALK" | "RUN" | "JUMP_START" | "JUMP_IDLE" | "JUMP_FALL" | "JUMP_LAND"

Accessing Character Animation Status (global store)

// You can track the current animation state of the character using the global animation store
import { useAnimationStore } from "bvhecctrl";

const animationStatus = useAnimationStore((state) => state.animationStatus); // "IDLE" | "WALK" | "RUN" | "JUMP_START" | "JUMP_IDLE" | "JUMP_FALL" | "JUMP_LAND"

// This value updates reactively and can be used in a useEffect:
useEffect(() => {
  console.log("Animation changed to:", animationStatus);
}, [animationStatus]);

💰 Support This Project

If you find BVHEcctrl helpful, please consider supporting the project.

Your support means a lot and will help me dedicate more time to development, improvements, and documentation.

Every bit of support helps! Whether it’s a donation, a star, or simply sharing the project. Thank you for helping me keep this project moving forward! 🙏

💡 What Add-ons Would You Like to See?

I’m considering offering additional features or paid extensions.
If you're interested, feel free to vote or leave feedback:

  • A vanilla three.js version of BVHEcctrl
  • Custom gravity support (move on spheres)
  • Tutorials on building this controller from scratch
  • More experimental features and playground demos

💬 Leave your thoughts on GitHub or join the discussion on the pmndrs Discord.