Created
November 23, 2021 17:23
-
-
Save mwmwmw/301477f9341f555e4fb6837f666244f6 to your computer and use it in GitHub Desktop.
A ReactXR controller for perpendicular sideways movement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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