For some reason the OnClick event is not working properly

I use R3F and Drei.
I’m trying to show/hide a PivotControl when I click on a specific object, but the click on the object doesn’t align with the mouse coordinates. What is wrong with the code below?

const MyObject = (props: IMyObject) => {
    const object: Object3D =;
    const trigRef = useRef<any>(null);
    const meshRef = useRef<Mesh>(null);
    const [visible, setVisible] = useState<boolean>(false);
    let _mouse = new Vector2();
    const raycaster = new Raycaster();
    const { camera  } = useThree();

    // UUID
    const uuid = object.uuid;

    // Get Size
    const size = new Box3().setFromObject(object);

    const onClick = () => {
        raycaster.setFromCamera(_mouse, camera);
        const intersects = raycaster.intersectObject(object);
        if (intersects.length > 0){
            console.log("OnClick Visible");
        else {
            console.log("OnClick Disable");

    const onDrag = (e) => {
        // 位置/回転率の確認
        const position = new Vector3().setFromMatrixPosition(e);
        const rotation = new Euler().setFromRotationMatrix(e);

    useEffect(() => {
        document.addEventListener("click", onClick);
        return () => {
            document.removeEventListener("click", onClick);
    }, []);

    useFrame(({ mouse }) => {

    return (
                onDrag={(e) => onDrag(e)}
                <mesh ref={meshRef}>
                    <primitive object={object} />

Here is the resulting GIF. For some reason,
Take a look at DevTools.“OnClick Visible” was displayed no matter where I clicked,
so I couldn’t detect clicks properly.

pointer events are ootb in fiber, why would you raycast for that?

and why wrap a primitive into a mesh?

the whole code above collapses into just this:

const [visible, setVisible] = useState(false)
return (
  <PivotControls visible={visible}>
    <primitive object={object} onClick={() => setVisible(!visible)} />

Thank you for your prompt reply!

Surely there may not have been a need to use Mesh.

Regarding the first question. I wrote it like this because I want the behavior to change “visible” to “false” when clicking outside the object. I would like to know if there is a way to detect out of beautiful “OnClick” bounds.

<primitive object={object} onPointerMissed={() => ...} />

ps here’s an example but it’s using the old three transformcontrols

1 Like

I actually tried and moved it.
worked perfectly.

It was very helpful.

Thank you for providing the sample which is very helpful.