Skip to content

Instantly share code, notes, and snippets.

@laffan
Last active February 26, 2023 08:15
Show Gist options
  • Save laffan/7ab4e4f47562f3f0e4f1af224bc52241 to your computer and use it in GitHub Desktop.
Save laffan/7ab4e4f47562f3f0e4f1af224bc52241 to your computer and use it in GitHub Desktop.
/*
Simple snap turn controller for anyone using the @react-three/xr
library on a Quest.
*/
import { useXR, useController } from "@react-three/xr";
import { useFrame } from "@react-three/fiber";
import { useState, useEffect } from "react";
function degToRad(degrees) {
var pi = Math.PI;
return degrees * (pi / 180);
}
function SnapController({
hand = "right",
repeatThreshold = 300,
turnDegrees = 30,
}) {
const { player } = useXR();
const controller = useController(hand);
const [actionAllowed, setActionAllowed] = useState(true);
useEffect(() => {
if (!actionAllowed) {
setTimeout(function () {
setActionAllowed(true);
}, repeatThreshold);
}
}, [actionAllowed]);
useFrame(() => {
if (controller && player) {
const { axes } = controller.inputSource.gamepad;
if (Math.abs(axes[2]) && actionAllowed) {
player.rotation.y -=
axes[2] > 0 ? degToRad(turnDegrees) : -degToRad(turnDegrees);
setActionAllowed(false);
}
}
});
return <></>;
}
export default SnapController;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment