事件

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"} />

悬停时改变颜色

现在,当鼠标悬停在球体上时,它会变成粉红色。

我们还可以使用 onClick 事件检测鼠标何时点击了某个 mesh。

我们添加一个状态来存储球体是否被选中:

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

然后,我们在 <mesh /> 组件上添加 onClick 事件:

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

我们将 selected 状态设置为其当前值的相反值。

最后,我们根据 selected 状态值有条件地更改 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

为了防止事件冒泡,我们可以在事件上使用 stopPropagation

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.