Making a wobbling cube in React using react-three-fiber


In this article, we will see how to make a wobbling cube in React, which will be wobbling in a loop and spinning at same time. We will first make a cube and then add the wobbling effect. We can also add a feature to make the cube wobble on hovering. So, let's get started.

Example

First download the react-three-fiber package −

npm i --save @react-three/fiber
npm i --save @react-three/drei
npm i --save three

threejs and react-three/fiber will be used to add webGL renderer to the website. react-three/fiber will be used to connect threejs and React. drei is used to add wobblingMesh.

Add the following lines of code in App.js

import React, { useRef } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import { MeshWobbleMaterial } from "@react-three/drei";

function Box(props) {
   const mesh = useRef();
   useFrame(() => (mesh.current.rotation.x = mesh.current.rotation.y += 0.01));
   return (
      <mesh {...props} ref={mesh}>
         <boxGeometry args={[3, 3, 3]} />
         <MeshWobbleMaterial
            attach="material"
            factor={1}
            speed={10}
            color={"lightblue"}/>
      </mesh>
   );
}

export default function App() {
   return (
      <Canvas>
         <ambientLight />
         <pointLight position={[10, 10, 10]} />
         <Box position={[0, 0, 0]} />
      </Canvas>
   );
}

Explanation

Here we first created a BoxGeometry object. Then in the material object we provided MeshWobbleMaterial which we imported from drei. The code is quite self-explanatory; we did some basic lighting and positioned the object.

<mesh> is used to create the threeJS object, and inside it, we made a box using boxGeometry which is used to define the size, shape and other structural parameters. We used meshWobbleMaterial to design our geometrical structure and to add the wobbling effect.

Output

On execution, it will produce the following output −

Updated on: 28-Sep-2021

420 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements