|
| 1 | +import { Physics, useBox, usePlane, useSphere } from '@react-three/cannon' |
| 2 | +import { Canvas } from '@react-three/fiber' |
| 3 | +import { OrbitControls } from '@react-three/drei' |
| 4 | + |
| 5 | +function BoxTrigger({ onCollide, size, position }) { |
| 6 | + const [ref] = useBox(() => ({ isTrigger: true, args: size, position, onCollide })) |
| 7 | + return ( |
| 8 | + <mesh castShadow ref={ref} position={position}> |
| 9 | + <boxBufferGeometry args={size} /> |
| 10 | + <meshStandardMaterial wireframe color="green" /> |
| 11 | + </mesh> |
| 12 | + ) |
| 13 | +} |
| 14 | + |
| 15 | +function Ball() { |
| 16 | + const [ref] = useSphere(() => ({ |
| 17 | + mass: 1, |
| 18 | + position: [0, 10, 0], |
| 19 | + args: 1, |
| 20 | + })) |
| 21 | + return ( |
| 22 | + <mesh castShadow receiveShadow ref={ref}> |
| 23 | + <sphereBufferGeometry args={[1, 16, 16]} /> |
| 24 | + <meshLambertMaterial color="white" /> |
| 25 | + </mesh> |
| 26 | + ) |
| 27 | +} |
| 28 | + |
| 29 | +function Plane(props) { |
| 30 | + const [ref] = usePlane(() => ({ type: 'Static', ...props })) |
| 31 | + return ( |
| 32 | + <mesh ref={ref} receiveShadow> |
| 33 | + <planeBufferGeometry args={[100, 100]} /> |
| 34 | + <shadowMaterial color="#171717" /> |
| 35 | + </mesh> |
| 36 | + ) |
| 37 | +} |
| 38 | + |
| 39 | +export default () => { |
| 40 | + return ( |
| 41 | + <Canvas shadows camera={{ position: [-10, 15, 5], material: { restitution: 10 }, fov: 50 }}> |
| 42 | + <color attach="background" args={['#171720']} /> |
| 43 | + <ambientLight intensity={0.3} /> |
| 44 | + <pointLight |
| 45 | + castShadow |
| 46 | + intensity={0.8} |
| 47 | + position={[100, 100, 100]} |
| 48 | + shadow-mapSize-width={2048} |
| 49 | + shadow-mapSize-height={2048} |
| 50 | + /> |
| 51 | + <OrbitControls /> |
| 52 | + <Physics> |
| 53 | + <BoxTrigger |
| 54 | + onCollide={(e) => { |
| 55 | + console.log('Collision event on BoxTrigger', e) |
| 56 | + }} |
| 57 | + position={[0, 5, 0]} |
| 58 | + size={[4, 1, 4]} |
| 59 | + /> |
| 60 | + <Ball /> |
| 61 | + <Plane rotation={[-Math.PI / 2, 0, 0]} /> |
| 62 | + </Physics> |
| 63 | + </Canvas> |
| 64 | + ) |
| 65 | +} |
0 commit comments