이벤트

Starter pack

React Three Fiber에서 마우스, 키보드 및 터치 이벤트를 처리하여 3D 장면을 더욱 상호 작용적이고 몰입감 있게 만드는 방법을 알아봅시다.

마우스

Meshes에는 마우스 이벤트를 처리하기 위한 몇 가지 이벤트가 있습니다.

마우스가 mesh 위에 있을 때를 감지하려면 onPointerEnteronPointerLeave 이벤트를 사용할 수 있습니다.

마우스가 구 위에 있을 때 구의 색상을 변경해 보겠습니다.

먼저 구에 마우스가 위에 있는지 여부를 저장하기 위해 상태를 생성합니다:

const [hovered, setHovered] = useState(false);

그런 다음 <mesh /> 컴포넌트에 onPointerEnteronPointerLeave 이벤트를 추가합니다:

<mesh
  {...props}
  onPointerEnter={() => setHovered(true)}
  onPointerLeave={() => setHovered(false)}
>
  {/* ... */}
</mesh>

마지막으로 hovered 상태 값을 기반으로 material의 색상을 조건부로 변경합니다:

<meshStandardMaterial color={hovered ? "pink" : "white"} />

마우스 오버 시 색상 변경

이제 마우스가 구 위에 있을 때 구가 분홍색으로 변합니다.

마우스가 mesh 위를 클릭했을 때를 onClick 이벤트를 사용하여 감지할 수도 있습니다.

구가 선택되었는지 여부를 저장하기 위해 상태를 추가합니다:

const [selected, setSelected] = useState(false);

그런 다음 <mesh /> 컴포넌트에 onClick 이벤트를 추가합니다:

<mesh
  {...props}
  onPointerEnter={() => setHovered(true)}
  onPointerLeave={() => setHovered(false)}
  onClick={() => setSelected(!selected)}
>
  {/* ... */}
</mesh>

selected 상태를 현재 값의 반대로 설정합니다.

마지막으로 active 상태 값을 기반으로 material의 색상을 조건부로 변경합니다:

let color = hovered ? "pink" : "white";
if (selected) {
  color = "hotpink";
}

return (
  <mesh
    {...props}
    onPointerEnter={() => setHovered(true)}
    onPointerLeave={() => setHovered(false)}
    onClick={() => setSelected(!selected)}
  >
    <sphereGeometry args={[0.5, 64, 64]} />
    <meshStandardMaterial color={color} />
  </mesh>
);

가독성을 높이기 위해 변수에 색상을 저장하여 두 개의 삼항 연산자를 사용하는 것보다 코드를 더 읽기 쉽게 만들었습니다.

이벤트 버블링

우리의 세 개의 구 뒤에 큰 구를 추가해 보겠습니다.

// ...

export const Experience = () => {
  return (
    <>
      <MoveableSphere scale={3} position-z={-10} />
      <MoveableSphere />
      <MoveableSphere position-x={-2} />
      <MoveableSphere position-x={2} />
      <ContactShadows
        rotation-x={Math.PI / 2}
        position={[0, -1.6, 0]}
        opacity={0.42}
      />

      <Environment preset="sunset" />
    </>
  );
};

중간 구를 가리키면 큰 구가 onPointerEnteronPointerLeave 이벤트에 의해 영향을 받는 것을 볼 수 있습니다. 이는 이러한 이벤트가 버블링되기 때문입니다.

마우스 이벤트를 감지하기 위해 React Three Fiber에서 사용되는 투사된 레이는 중간 구를 지나 큰 구로 이어집니다.

bubbleEvent

이벤트가 버블링되는 것을 방지하려면, eventstopPropagation을 사용할 수 있습니다.

Three.js logoReact logo

React Three Fiber: The Ultimate Guide to 3D Web Development

✨ You have reached the end of the preview ✨

Go to the next level with Three.js and React Three Fiber!

Get full access to this lesson and the complete course when you enroll:

  • 🔓 Full lesson videos with no limits
  • 💻 Access to the final source code
  • 🎓 Course progress tracking & completion
  • 💬 Invite to our private Discord community
Unlock the Full Course – Just $85

One-time payment. Lifetime updates included.