3D Cube with Three.js
Explore a rotating 3D cube created using Three.js and React Three Fiber.
Playground
What I Learned
In this playground, I explored the basics of creating a 3D scene using Three.js and React Three Fiber. I learned how to create a simple cube geometry, add materials, and implement rotation animation.
Here's the key part of the code that creates and animates the cube:
function Cube() {
const meshRef = useRef<THREE.Mesh>(null!);
const edgesRef = useRef<THREE.LineSegments>(null!);
useFrame((state, delta) => {
meshRef.current.rotation.x += delta * 0.5;
meshRef.current.rotation.y += delta * 0.5;
edgesRef.current.rotation.x += delta * 0.5;
edgesRef.current.rotation.y += delta * 0.5;
});
return (
<group>
<mesh ref={meshRef}>
<boxGeometry args={[2, 2, 2]} />
<meshBasicMaterial color="hotpink" />
</mesh>
<lineSegments ref={edgesRef}>
<edgesGeometry args={[new THREE.BoxGeometry(2, 2, 2)]} />
<lineBasicMaterial color="black" linewidth={2} />
</lineSegments>
</group>
);
}
This code creates a cube with a hot pink material and black edges. The `useFrame` hook is used to rotate the cube on each frame, creating the animation effect.
Challenges Faced
One of the main challenges was understanding how to properly use refs with Three.js objects in a React context. I also had to figure out how to add edges to the cube to make its shape more distinct.
Future Improvements
In the future, I'd like to add more complex geometries and implement interactive features, such as changing the cube's color or shape based on user input. I'm also interested in exploring more advanced Three.js features like custom shaders and post-processing effects.