【问题标题】:How to filter on-click in react three js?如何在反应三个js中过滤点击?
【发布时间】:2021-09-07 00:34:01
【问题描述】:

所以我探索2 cubes sample。我想一次只点击一个立方体。然而,当我点击一个立方体时,它的后面有一个立方体,两者都被点击了。如何强制单击并仅将鼠标悬停在最近的一个上?

换句话说,在立方体 A 上单击\悬停我希望不要单击立方体 B

我的代码示例:

import React, { useRef, useState } from 'react'
import { Canvas, useFrame } from '@react-three/fiber'

function Box(props) {
  // This reference will give us direct access to the mesh
  const mesh = useRef()
  // Set up state for the hovered and active state
  const [hovered, setHover] = useState(false)
  const [active, setActive] = useState(false)
  // Rotate mesh every frame, this is outside of React without overhead
  useFrame(() => {
    mesh.current.rotation.x = mesh.current.rotation.y += 0.01
  })
  return (
    <mesh
      {...props}
      ref={mesh}
      scale={active ? 1.5 : 1}
      onClick={(e) => setActive(!active)}
      onPointerOver={(e) => setHover(true)}
      onPointerOut={(e) => setHover(false)}>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
    </mesh>
  )
}

export default function App() {
  return (
    <Canvas>
      <ambientLight intensity={0.5} />
      <spotLight position={[10, 10, 10]} angle={0.15} penumbra={1} />
      <pointLight position={[-10, -10, -10]} />
      <Box position={[1.2, 0.5, 0]} />
      <Box position={[1.2, 0, 0]} />
    </Canvas>
  )
}

【问题讨论】:

  • 你的两个立方体都定义在一个几何体中吗?
  • 分享一些代码会很有帮助
  • @AbdullahKhan:添加代码示例
  • 我测试了您的代码,默认行为似乎是合理的,如果您将鼠标悬停在相交区域上,则唯一一个同时突出显示两个框的区域。但是,如果您将鼠标悬停在任何其他区域上,它似乎会突出显示该立方体
  • 不确定您的要求是什么,但也许您想将这些立方体分开

标签: javascript reactjs three.js react-three-fiber


【解决方案1】:

解决了here

主要差异:

function intersectionsFilter(intersections) {
  return intersections?.length ? [intersections[0]] : intersections
}

export default function App() {
  return (
    <Canvas raycaster={{ filter: intersectionsFilter }}>

【讨论】:

  • 如果使用带有 react 的事件,你也可以使用 e.stopPropagation();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
相关资源
最近更新 更多