reactjsthree.jsreact-three-fiber

React Three Fiber, How to track mouse movement


I am trying to use three for the first time to level up my webpages a little so I'm following a guide on YouTube here so you can see what I'm trying to accomplish. https://www.youtube.com/watch?v=YK1Sw_hnm58 I'm at around 1:12:20. the only difference is I'm using react instead of plain JavaScript so I'm struggling to convert it since I've never used it before.

/* eslint-disable no-unused-vars */
import React, { useRef } from "react";
import { useFrame, useLoader } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
import * as THREE from "three";
import { useEffect } from "react";
import { useState } from "react";

const PlaneMesh = (params) => {
  const paneRef = useRef();

  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(false)
    const { array } = paneRef.current.geometry.attributes.position

    for (let i = 0; i < array.length; i += 3){
      array[i + 2] = array[i + 2] + Math.random()
    }

  }, [loading])


  const [MousePosition, setMousePosition] = useState({
    left: 0,
    top: 0
})
 
useFrame( state  => {
  let mouseX = state.mouse.x;
  let mouseY = state.mouse.y;

  
  console.log(mouseX)
});

  return (
    <>
      {/* <ambientLight intensity={1} /> */}
      <directionalLight color={0xFFFFFF} position={[0, 0, 1]} intensity={1} />
      {/* <pointLight color="#FFFFFF" position={[0, 0, 2]} intensity={1} /> */}

      <mesh ref={paneRef} position={[0,0, -5]}>
        <planeGeometry args={[100, 100, 50, 50]} />
        <meshPhongMaterial
          color={0x000044}
          side={THREE.DoubleSide}
          flatShading={true}
        />
        {/* <OrbitControls
          enableZoom={true}
          enablePan={true}
          enableRotate={true}
          zoomSpeed={0.6}
          panSpeed={0.5}
          rotateSpeed={0.4}
        /> */}
      </mesh>
    </>
  );
};

export default PlaneMesh;

This is my full file right now. I cant work out how to add the mouse move event listener and have it work as any method I have tried either only runs once or only runs when I click on the page rather than when I move the mouse. This is the closest I have been able to get it as it constantly prints the value but the mouse coordinates don't update unless I click. Any advice is greatly appreciated.


Solution

  • I ended up fixing it by adding a window event listener and subtracting the bounding box to get the mouse position over the element.

    const section = document.getElementById("planeSection");
    
        section.addEventListener("mousemove", (event) => {
          var rect = container.getBoundingClientRect();
          mouse.x = ((event.clientX - rect.left) / window.innerWidth) * 2 - 1;
          mouse.y = -((event.clientY - rect.top) / window.innerHeight) * 2 + 1;
        });