Skip to content

Instantly share code, notes, and snippets.

@mwmwmw
Created November 23, 2021 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwmwmw/55a8631ef4a28e9bccb627a94f53a6b2 to your computer and use it in GitHub Desktop.
Save mwmwmw/55a8631ef4a28e9bccb627a94f53a6b2 to your computer and use it in GitHub Desktop.
A ReactXR component for moving around. Forward will always move in the direction you are looking.
import { useXR, useController, useXRFrame } from '@react-three/xr';
import { Vector3 } from 'three';
import { useRef } from 'react';
export default function BasicMovementController ({
hand = 'right',
sensitivity = 0.05,
zeroY = true,
}) {
const { player } = useXR();
const controller = useController(hand);
const forward = useRef(new Vector3());
useXRFrame(() => {
if (controller && player) {
const { axes } = controller.inputSource.gamepad;
const camera = player.children[0];
const cameraMatrix = camera.matrixWorld.elements;
forward.current
.set(-cameraMatrix[8], -cameraMatrix[9], -cameraMatrix[10])
.normalize();
if (zeroY) {
forward.current.y = 0;
}
player.position.add(
forward.current.multiplyScalar(-axes[3] * sensitivity),
);
player.rotation.y -= axes[2] * sensitivity;
}
});
return <></>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment