Skip to content

Instantly share code, notes, and snippets.

@jamesporter
Last active July 18, 2020 09:17
Show Gist options
  • Save jamesporter/00181102236822adaeae1ef7233013f3 to your computer and use it in GitHub Desktop.
Save jamesporter/00181102236822adaeae1ef7233013f3 to your computer and use it in GitHub Desktop.
PoC react-xr (react-three-fiber) demo
import Head from "next/head";
import { VRCanvas, DefaultXRControllers, useXR, Hover, Select } from "react-xr";
import { useFrame } from "react-three-fiber";
import { useState, useRef } from "react";
function Box({
size = 1,
position = [0, 0, 0],
}: {
size?: number;
position?: [number, number, number];
}) {
const [hovering, setHovering] = useState(false);
const [selected, setSelected] = useState(false);
const mesh = useRef();
useFrame(() => (mesh.current.rotation.x = mesh.current.rotation.y += 0.01));
return (
<Hover onChange={setHovering}>
<Select onSelect={() => setSelected(!selected)}>
<mesh position={position} scale={[size, size, size]} ref={mesh}>
<boxBufferGeometry attach="geometry" args={[1, 1, 1]} />
<meshStandardMaterial
attach="material"
color={hovering ? "red" : selected ? "#e9e9e9" : "orange"}
/>
</mesh>
</Select>
</Hover>
);
}
function Floor() {
return (
<mesh position={[0, 0, 0]} scale={[10, 0.1, 10]}>
<boxBufferGeometry attach="geometry" args={[1, 1, 1]} />
<meshStandardMaterial attach="material" color={"#a5a5a5"} />
</mesh>
);
}
const randomPosition = (scale = 5): [number, number, number] => {
return [
Math.random() * scale - scale / 2,
Math.random() * scale + 0.1,
Math.random() * scale - scale / 2,
];
};
const positions: [number, number, number][] = [];
for (let i = 0; i < 200; i++) {
positions.push(randomPosition());
}
export default function Home() {
const { controllers } = useXR();
return (
<div className="container">
<Head>
<title>Exploring WebVR with React-Three-Fiber</title>
<link rel="icon" href="/vivarium.svg" />
</Head>
<main>
<div className="containar">
<h1>Exploring WebVR with React-Three-Fiber</h1>
<VRCanvas>
<DefaultXRControllers />
<ambientLight intensity={0.2} />
<pointLight position={[10, 10, 10]} />
{positions.map((p, i) => (
<Box position={p} key={i} size={0.1} />
))}
<Floor />
</VRCanvas>
</div>
</main>
<footer></footer>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment