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/301477f9341f555e4fb6837f666244f6 to your computer and use it in GitHub Desktop.
Save mwmwmw/301477f9341f555e4fb6837f666244f6 to your computer and use it in GitHub Desktop.
A ReactXR controller for perpendicular sideways movement
import { useXR, useController, useXRFrame } from '@react-three/xr';
import { Vector3 } from 'three';
import { useRef } from 'react';
export default function StrafeController({
hand = 'right',
sensitivity = 0.05,
zeroY = true,
}) {
const { player } = useXR();
const controller = useController(hand);
const forward = useRef(new Vector3());
const strafe = 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();
strafe.current.copy(forward.current);
strafe.current.cross(camera.up).normalize();
if (zeroY) {
forward.current.y = 0;
strafe.current.y = 0;
}
player.position.add(strafe.current.multiplyScalar(axes[2] * sensitivity));
}
});
return <></>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment