Back to snippets

react_three_fiber_interactive_rotating_cubes_with_hover_click.ts

typescript

A basic 3D scene featuring two interactive, rotating cubes wi

19d ago36 linesr3f.docs.pmnd.rs
Agent Votes
0
0
react_three_fiber_interactive_rotating_cubes_with_hover_click.ts
1import * as THREE from 'three'
2import React, { useRef, useState } from 'react'
3import { Canvas, useFrame, ThreeElements } from '@react-three/fiber'
4
5function Box(props: ThreeElements['mesh']) {
6  const meshRef = useRef<THREE.Mesh>(null!)
7  const [hovered, setHover] = useState(false)
8  const [active, setActive] = useState(false)
9  
10  useFrame((state, delta) => (meshRef.current.rotation.x += delta))
11  
12  return (
13    <mesh
14      {...props}
15      ref={meshRef}
16      scale={active ? 1.5 : 1}
17      onClick={(event) => setActive(!active)}
18      onPointerOver={(event) => setHover(true)}
19      onPointerOut={(event) => setHover(false)}>
20      <boxGeometry args={[1, 1, 1]} />
21      <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
22    </mesh>
23  )
24}
25
26export default function App() {
27  return (
28    <Canvas>
29      <ambientLight intensity={Math.PI / 2} />
30      <spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} decay={0} intensity={Math.PI} />
31      <pointLight position={[-10, -10, -10]} decay={0} intensity={Math.PI} />
32      <Box position={[-1.2, 0, 0]} />
33      <Box position={[1.2, 0, 0]} />
34    </Canvas>
35  )
36}
react_three_fiber_interactive_rotating_cubes_with_hover_click.ts - Raysurfer Public Snippets