React.js Three.js React_Three_fibre RayCaster How use RayCaster in R3f React js

แชร์
ฝัง
  • เผยแพร่เมื่อ 20 ธ.ค. 2024

ความคิดเห็น • 1

  • @paradise_hope
    @paradise_hope  2 วันที่ผ่านมา

    import { useRef, useState, useEffect } from "react";
    import { Canvas, useFrame } from '@react-three/fiber'
    import { OrbitControls } from "@react-three/drei";
    import { useThree } from '@react-three/fiber'
    import React, { Suspense, useMemo } from 'react'
    import useRefs from 'react-use-refs'
    import * as THREE from 'three'
    import { AxesHelper } from 'three'; // Import AxesHelper from three.js
    import { Grid ,Axes} from '@react-three/drei';
    function Box({ position }) {
    const boxRef = useRef();
    const { scene } = useThree() // Access the scene
    //const raycaster = new THREE.Raycaster(new THREE.Vector3(0,0, 0), new THREE.Vector3(1, 0, 0));
    //const raycaster = new THREE.Raycaster();
    const origin = new THREE.Vector3(0, 0, 0)
    const direction = new THREE.Vector3(-.1, 0, 0)
    // Set the ray's origin and direction
    //raycaster.ray.origin.copy(origin);
    //raycaster.ray.direction.copy(direction);
    const raycaster = new THREE.Raycaster(origin,direction);
    useFrame(() => {
    //const intersections = raycaster.intersectObjects(scene.children);
    //const intersections1 = raycaster.intersectObjects(scene.children);
    const intersections = raycaster.intersectObjects(scene.children);
    [boxRef].forEach((ref) => {
    ref.current.material.color.set('red')
    })
    for (const intersect of intersections) {
    console.log("khan",intersect.object)
    intersect.object.material.color.set('green')
    }
    /* for (const intersect of intersections1) {
    console.log("tahzeeb",intersect.object)
    intersect.object.material.color.set('green')
    } */
    })
    return (


    );
    }
    function GroundPlane() {
    return (


    );
    }
    function Scene() {
    const [position, setPosition] = useState([0, 0.5, 0]);
    useEffect(() => {
    const handleKeyDown = (event) => {
    setPosition((prev) => {
    const [x, y, z] = prev;
    const step = 0.5;
    switch (event.key) {
    case "w":
    return [x, y, z - step]; // Move forward
    case "s":
    return [x, y, z + step]; // Move backward
    case "a":
    return [x - step, y, z]; // Move left
    case "d":
    return [x + step, y, z]; // Move right
    default:
    return prev;
    }
    });
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
    }, []);
    return (



    );
    }
    export default function App() {
    return (


    );
    }