Created
November 23, 2021 17:23
-
-
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.
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 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