• Stars
    star
    498
  • Rank 88,494 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 1 year ago
  • Updated 4 months ago

Reviews

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

Repository Details

🕹️ A floating rigibody character controller

Ecctrl Floating Capsule Character Controller

screenshot

Pmndrs/ecctrl is a simple web based character controller build on react-three-fiber and react-three-rapier. It provides a playground demo where you can experience the following features:

  1. Seamless movement over small obstacles
  2. Enhanced control with floating force incorporating spring and damping forces
  3. Rigidbody character functionality for interaction with the game environment
  4. Customizable ground friction for tailored control
  5. Realistic simulation with applied mass on supporting surfaces
  6. Smooth integration with moving and rotating platforms

New Features

(2024-1-1) EcctrlMode:

  • Now you can seamlessly switch between different modes by adding "mode" inside Ecctrl.

<Ecctrl mode="PointToMove">

  • "PointToMove" mode is designed for click-to-move or path following features. (no needs for keyboard controls)
import { useGame } from "ecctrl";
// ...
const setMoveToPoint = useGame((state) => state.setMoveToPoint);
// ...
// call function setMoveToPoint(), whenever character needs to move
setMoveToPoint(point); // "point" is a vec3 value

screenshot

Check out the featurelog.md for details on previous updates and features.

Project Link

Live Demo: Floating Capsule Character Controller

Local Setup

Download Node.js. Run this followed commands:

# Install dependencies (only the first time)
npm install

# Run the local server at localhost:5173
npm run dev

# Build for production in the example/exampleDist/ directory
vite build -c vercelVite.config.js

How To Use

Basic Controls (CodeSandbox Demo)

npm install ecctrl
import Ecctrl, { EcctrlAnimation } from "ecctrl";

To get started, set up your keyboard map using KeyboardControls. Then, wrap your character model within <Ecctrl>:

/**
 * Keyboard control preset
 */
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"] },
  // Optional animation key map
  { name: "action1", keys: ["1"] },
  { name: "action2", keys: ["2"] },
  { name: "action3", keys: ["3"] },
  { name: "action4", keys: ["KeyF"] },
];

return (
  <>
    ...
    <Physics debug={physics} timeStep="vary">
      {/* Keyboard preset */}
      <KeyboardControls map={keyboardMap}>
        {/* Character Control */}
        <Ecctrl>
          {/* Replace your model here */}
          <CharacterModel />
        </Ecctrl>
      </KeyboardControls>
      ...
    </Physics>
  </>
);

Here are all the default properties you can play with for <Ecctrl>:

// Default properties for Ecctrl
EcctrlProps: {
  children, // ReactNode
  debug: false, // Enable debug mode (require leva package)
  capsuleHalfHeight: 0.35, // Half-height of the character capsule
  capsuleRadius: 0.3, // Radius of the character capsule
  floatHeight: 0.3, // Height of the character when floating
  characterInitDir: 0, // Character initial facing direction (in rad)
  followLight: false, // Enable follow light mode (name your light "followLight" before turn this on)
  disableFollowCam: false, // Disable follow camera feature
  disableFollowCamPos: { x: 0, y: 0, z: -5 }, // Camera position when the follow camera feature is disabled
  disableFollowCamTarget: { x: 0, y: 0, z: 0 }, // Camera lookAt target when the follow camera feature is disabled
  // Follow camera setups
  camInitDis: -5, // Initial camera distance
  camMaxDis: -7, // Maximum camera distance
  camMinDis: -0.7, // Minimum camera distance
  camInitDir: { x: 0, y: 0, z: 0 }, // Camera initial rotation direction (in rad)
  camTargetPos: { x: 0, y: 0, z: 0 }, // Camera target position
  camMoveSpeed: 1, // Camera moving speed multiplier
  camZoomSpeed: 1, // Camera zooming speed multiplier
  camCollision: true, // Camera collision active/deactive
  camCollisionOffset: 0.7, // Camera collision offset
   // Follow light setups
  followLightPos: { x: 20, y: 30, z: 10 }, // Follow light position
  // Base control setups
  maxVelLimit: 2.5, // Maximum velocity limit
  turnVelMultiplier: 0.2, // Turn velocity multiplier
  turnSpeed: 15, // Turn speed
  sprintMult: 2, // Sprint speed multiplier
  jumpVel: 4, // Jump velocity
  jumpForceToGroundMult: 5, // Jump force to ground object multiplier
  slopJumpMult: 0.25, // Slope jump affect multiplier
  sprintJumpMult: 1.2, // Sprint jump multiplier
  airDragMultiplier: 0.2, // Air drag multiplier
  dragDampingC: 0.15, // Drag damping coefficient
  accDeltaTime: 8, // Acceleration delta time
  rejectVelMult: 4, // Reject velocity multiplier
  moveImpulsePointY: 0.5, // Move impulse point Y offset
  camFollowMult: 11, // Camera follow speed multiplier
  fallingGravityScale: 2.5, // Character is falling, apply higher gravity
  fallingMaxVel: -20, // Limit character max falling velocity
  wakeUpDelay: 200, // Wake up character delay time after window visibility change to visible (in ms)
  // Floating Ray setups
  rayOriginOffest: { x: 0, y: -capsuleHalfHeight, z: 0 }, // Ray origin offset
  rayHitForgiveness: 0.1, // Ray hit forgiveness
  rayLength: capsuleRadius + 2, // Ray length
  rayDir: { x: 0, y: -1, z: 0 }, // Ray direction
  floatingDis: capsuleRadius + floatHeight, // Floating distance
  springK: 1.2, // Spring constant
  dampingC: 0.08, // Damping coefficient
  // Slope Ray setups
  showSlopeRayOrigin: false, // Show slope ray origin
  slopeMaxAngle: 1, // in rad, the max walkable slope angle
  slopeRayOriginOffest: capsuleRadius - 0.03, // Slope ray origin offset
  slopeRayLength: capsuleRadius + 3, // Slope ray length
  slopeRayDir: { x: 0, y: -1, z: 0 }, // Slope ray direction
  slopeUpExtraForce: 0.1, // Slope up extra force
  slopeDownExtraForce: 0.2, // Slope down extra force
  // AutoBalance Force setups
  autoBalance: true, // Enable auto-balance
  autoBalanceSpringK: 0.3, // Auto-balance spring constant
  autoBalanceDampingC: 0.03, // Auto-balance damping coefficient
  autoBalanceDampingOnY: 0.02, // Auto-balance damping on Y-axis
  // Animation temporary setups
  animated: false, // Enable animation
  // Mode setups
  mode: null, // Activate different ecctrl modes
  // Customizable controller key setups
  controllerKeys: { forward: 12, backward: 13, leftward: 14, rightward: 15, jump: 2, action1: 11, action2: 3, action3: 1, action4: 0 },
  // Other rigibody props from parent
  // Rigidbody props can be used here,
  // such as position, friction, gravityScale, etc.
  ...props
}

// Simply change the value by doing this
<Ecctrl maxVelLimit={5} jumpVel={4} position={[0,10,0]}>
  <CharacterModel />
</Ecctrl>

Apply Character Animations (CodeSandbox Demo)

If you want to apply character animations, prepare the character url and customize the animationSet with your own animation names. Change the Ecctrl property animated to true and wrap your character model inside <EcctrlAnimation> tag:

// Prepare character model url
const characterURL = "./ReplaceWithYourCharacterURL";

// Prepare and rename your character animations here
// Note: idle, walk, run, jump, jumpIdle, jumpLand and fall names are essential
// Missing any of these names might result in an error: "cannot read properties of undifined (reading 'reset')"
const animationSet = {
  idle: "Idle",
  walk: "Walk",
  run: "Run",
  jump: "Jump_Start",
  jumpIdle: "Jump_Idle",
  jumpLand: "Jump_Land",
  fall: "Climbing", // This is for falling from high sky
  // Currently support four additional animations
  action1: "Wave",
  action2: "Dance",
  action3: "Cheer",
  action4: "Attack(1h)", // This is special action which can be trigger while walking or running
};

return (
  <>
    ...
    <Physics debug={physics} timeStep="vary">
      {/* Keyboard preset */}
      <KeyboardControls map={keyboardMap}>
        {/* Character Control */}
        <Ecctrl animated>
          {/* Character Animations */}
          <EcctrlAnimation
            characterURL={characterURL} // Must have property
            animationSet={animationSet} // Must have property
          >
            {/* Replace your model here */}
            <CharacterModel />
          </EcctrlAnimation>
        </Ecctrl>
      </KeyboardControls>
      ...
    </Physics>
  </>
);

(Advanced) Add and Personalize Additional Animations

For advanced animation setups, download all files and follow these steps:

  1. In CharacterModel.jsx, expand the animationSet with additional animations:
// Rename your character animations here
const animationSet = {
  idle: "Idle",
  walk: "Walk",
  run: "Run",
  jump: "Jump_Start",
  jumpIdle: "Jump_Idle",
  jumpLand: "Jump_Land",
  fall: "Climbing",
  action1: "Wave",
  action2: "Dance",
  action3: "Cheer",
  action4: "Attack(1h)", // This is special action which can be trigger while walking or running
  //additinalAnimation: "additinalAnimationName",
};
  1. In useGame.jsx, create a trigger function for the new animation:
  return {
      /**
       * Character animations state manegement
       */
      // Initial animation
      curAnimation: null,
      animationSet: {},

      ...

      action1: () => {
        set((state) => {
          if (state.curAnimation === state.animationSet.idle) {
            return { curAnimation: state.animationSet.action1 };
          }
          return {};
        });
      },

      /**
       * Additional animations
       */
      // triggerFunction: ()=>{
      //    set((state) => {
      //        return { curAnimation: state.animationSet.additionalAnimation };
      //    });
      // }
    };
  1. In CharacterController.jsx, initialize the trigger function and call it when needed:
// Animation change functions
const idleAnimation = useGame((state) => state.idle);
const walkAnimation = useGame((state) => state.walk);
const runAnimation = useGame((state) => state.run);
const jumpAnimation = useGame((state) => state.jump);
const jumpIdleAnimation = useGame((state) => state.jumpIdle);
const jumpLandAnimation = useGame((state) => state.jumpLand);
const fallAnimation = useGame((state) => state.fall);
const action1Animation = useGame((state) => state.action1);
const action2Animation = useGame((state) => state.action2);
const action3Animation = useGame((state) => state.action3);
const action4Animation = useGame((state) => state.action4);
//const additionalAnimation = useGame((state) => state.triggerFunction);

EcctrlJoystick and Touch buttons

To get start, simply import EcctrlJoystick from ecctrl

import { EcctrlJoystick } from "ecctrl";

Place <EcctrlJoystick> outside of your canvas component, and you're done!

//...
  <EcctrlJoystick />
  <Canvas>
    {/* ... */}
  </Canvas>
//...

You can also add lights or additional meshs like so (note: this will create components twice, once inside the joystick's scene, another inside the buttons' scene, so keep an eye on performance):

//...
  <EcctrlJoystick>
    <ambientLight />
    <mesh>
      <boxGeometry args={[1,1,1]} />
    </mesh>
  </EcctrlJoystick>
  <Canvas>
    {/* ... */}
  </Canvas>
//...

Additionally, you can change components' material, geometry, or texture as you like:

//...
  <EcctrlJoystick
    joystickBaseProps={{
      receiveShadow: true,
      material: new THREE.MeshStandardMaterial({ color: "grey" })
    }}
  />
  <Canvas>
    {/* ... */}
  </Canvas>
//...

Here are all the properties you can play with for <EcctrlJoystick>:

EcctrlJoystickProps: {
    // Joystick props
    children?: ReactNode;
    joystickPositionLeft?: number; // joystick div container position left
    joystickPositionBottom?: number; // joystick div container position bottom
    joystickHeightAndWidth?: number; // joystick div container height and width
    joystickCamZoom?: number; // camera zoom level for the joystick
    joystickCamPosition?: [x: number, y: number, z: number]; // camera position for the joystick
    joystickBaseProps?: ThreeElements['mesh']; // custom properties for the joystick's base mesh
    joystickStickProps?: ThreeElements['mesh']; // custom properties for the joystick's stick mesh
    joystickHandleProps?: ThreeElements['mesh']; // custom properties for the joystick's handle mesh

    // Touch buttons props
    buttonNumber?: number; // Number of buttons (max 5)
    buttonPositionRight?: number; // buttons div container position right
    buttonPositionBottom?: number; // buttons div container position bottom
    buttonHeightAndWidth?: number; // buttons div container height and width
    buttonCamZoom?: number; // camera zoom level for the buttons
    buttonCamPosition?: [x: number, y: number, z: number]; // camera position for the buttons
    buttonGroup1Position?: [x: number, y: number, z: number]; // button 1 posiiton in 3D scene
    buttonGroup2Position?: [x: number, y: number, z: number]; // button 2 posiiton in 3D scene
    buttonGroup3Position?: [x: number, y: number, z: number]; // button 3 posiiton in 3D scene
    buttonGroup4Position?: [x: number, y: number, z: number]; // button 4 posiiton in 3D scene
    buttonGroup5Position?: [x: number, y: number, z: number]; // button 5 posiiton in 3D scene
    buttonLargeBaseProps?: ThreeElements['mesh']; // custom properties for the buttons' large base mesh
    buttonSmallBaseProps?: ThreeElements['mesh']; // custom properties for the buttons' small base mesh
    buttonTop1Props?: ThreeElements['mesh']; // custom properties for the button 1 top mesh (large button)
    buttonTop2Props?: ThreeElements['mesh']; // custom properties for the button 2 top mesh (large button)
    buttonTop3Props?: ThreeElements['mesh']; // custom properties for the button 3 top mesh (small button)
    buttonTop4Props?: ThreeElements['mesh']; // custom properties for the button 4 top mesh (small button)
    buttonTop5Props?: ThreeElements['mesh']; // custom properties for the button 5 top mesh (small button)
};

Using your own joystick or buttons

If you prefer to use your custom joystick or buttons, you can leverage the useJoystickControls hook from ecctrl. Import the hook and call the appropriate functions::

import { useJoystickControls } from "ecctrl";
//...
const setJoystick = useJoystickControls((state) => state.setJoystick);
const resetJoystick = useJoystickControls((state) => state.resetJoystick);
const pressButton1 = useJoystickControls((state) => state.pressButton1);
const releaseAllButtons = useJoystickControls(
  (state) => state.releaseAllButtons
);
//...
// call the proper fuctions
setJoystick(joystickDis, joystickAng, runState);
// or
pressButton1();

Ecctrl Mode

Activate different modes in Ecctrl by including the desired mode inside Ecctrl component: <Ecctrl mode="PointToMove">.

1. "PointToMove" Mode (CodeSandbox Demo)

This mode doesn't require keyboard controls and is designed for click-to-move or path-following features.

import { useGame } from "ecctrl";
// ...
const setMoveToPoint = useGame((state) => state.setMoveToPoint);
// ...
// call function setMoveToPoint(), whenever character needs to move
setMoveToPoint(point); // "point" is a vec3 value

(Optional) First-person view setup

If you would like to quickly set up a first-person mode, you can modify these props to achieve that:

<Ecctrl
  camInitDis={-0.01} // camera intial position
  camMinDis={-0.01} // camera zoom in closest position
  camFollowMult={100} // give any big number here, so the camera follows the character instantly
  turnVelMultiplier={1} // Turning speed same as moving speed
  turnSpeed={100} // give it big turning speed to prevent turning wait time
  mode="CameraBasedMovement" // character's rotation will follow camera's rotation in this mode
>

Contributions

I appreciate your interest in this project! If you have any feedback, suggestions, or resources related to the controller, please feel free to share.

Thank you!

More Repositories

1

zustand

🐻 Bear necessities for state management in React
TypeScript
45,348
star
2

react-spring

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

react-three-fiber

🇨🇭 A React renderer for Three.js
TypeScript
26,202
star
4

jotai

👻 Primitive and flexible state management for React
TypeScript
18,007
star
5

use-gesture

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

valtio

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

drei

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

leva

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

gltfjsx

🎮 Turns GLTFs into JSX components
JavaScript
4,251
star
10

use-cannon

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

react-three-next

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

postprocessing

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

racing-game

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

xr

🤳 VR/AR for react-three-fiber
TypeScript
2,051
star
15

uikit

🎨 user interfaces for react-three-fiber
TypeScript
2,048
star
16

react-three-flex

💪📦 Flexbox for react-three-fiber
TypeScript
1,640
star
17

suspend-react

🚥 Async/await for React components
TypeScript
1,358
star
18

react-postprocessing

📬 postprocessing for react-three-fiber
JavaScript
1,074
star
19

detect-gpu

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

react-three-rapier

🤺 Rapier physics in React
TypeScript
1,005
star
21

lamina

🍰 An extensible, layer based shader material for ThreeJS
TypeScript
1,005
star
22

its-fine

🐶🔥 A collection of escape hatches for React.
TypeScript
978
star
23

react-use-measure

🙌 Utility to measure view bounds
TypeScript
832
star
24

react-nil

⃝ A react null renderer
TypeScript
785
star
25

maath

🪶 Math helpers for the rest of us
TypeScript
783
star
26

threejs-journey

⚛️ Bruno Simons journey demos in React
TypeScript
718
star
27

three-stdlib

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

react-three-editor

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

react-three-a11y

♿️ Accessibility tools for React Three Fiber
TypeScript
534
star
30

react-three-offscreen

📺 Offscreen worker canvas for react-three-fiber
TypeScript
443
star
31

react-zdog

⚡️🐶 React bindings for zdog
JavaScript
441
star
32

drei-vanilla

🍦 drei-inspired helpers for threejs
TypeScript
436
star
33

use-asset

📦 A promise caching strategy for React Suspense
TypeScript
413
star
34

tunnel-rat

🐀 Non gratum anus rodentum
TypeScript
329
star
35

react-three-csg

🚧 Constructive solid geometry for React
TypeScript
264
star
36

react-three-lgl

🔆 A React abstraction for the LGL Raycaster
TypeScript
262
star
37

gltf-react-three

Convert GLTF files to React Three Fiber Components
JavaScript
258
star
38

market

📦 Download CC0 assets ready to use in your next 3D Project
JavaScript
250
star
39

component-material

🧩 Compose modular materials in React
TypeScript
160
star
40

env

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

react-ogl

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

use-p2

👋💣 2d physics hooks for @react-three/fiber
TypeScript
144
star
43

react-spring-examples

JavaScript
139
star
44

react-three-gpu-pathtracer

⚡️ A React abstraction for the popular three-gpu-pathtracer
TypeScript
132
star
45

react-three-lightmap

In-browser lightmap/AO baker for react-three-fiber and ThreeJS
TypeScript
127
star
46

cannon-es-debugger

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

rafz

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

docs

🖨️ mdx documentation generator for `pmndrs/*/docs` folders
TypeScript
91
star
49

assets

📦 Importable base64 encoded CC0 assets
Makefile
91
star
50

swc-jotai

Rust
88
star
51

react-three-jolt

⚡ Jolt physics in React
TypeScript
84
star
52

react-three-scissor

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

eslint-plugin-valtio

An eslint plugin for better valtio experience
JavaScript
74
star
54

react-three-babel

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

react-spring.io

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

r3f-website

Website for React Three Fiber
JavaScript
27
star
57

directed

A flexible, minimal scheduler written in TypeScript
TypeScript
24
star
58

market-assets

JavaScript
19
star
59

react-three-8thwall

JavaScript
17
star
60

drei-assets

JavaScript
16
star
61

discord

🤖 Poimandres Discord Bot
TypeScript
10
star
62

branding

TypeScript
7
star
63

market-assets-do

JavaScript
5
star
64

envinfo

Easily collect useful information for bug reports
JavaScript
4
star
65

leva-wg

1
star