Three.js: get intersection position of Mouseover

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Mouseover</title>
    <style>
        body {
            margin: 0;
        }
    </style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r126/three.js"></script>
<script type="module">
    import {Text} from 'https://unpkg.com/troika-three-text@0.41.1/dist/troika-three-text.esm.js?module';

    const scene = new THREE.Scene();

    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.x = 2;
    camera.position.y = 2;
    camera.position.z = 5;

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    const geometry = new THREE.BoxGeometry();
    const material = new THREE.MeshBasicMaterial({color: 0x00ff00});
    const cube = new THREE.Mesh(geometry, material);
    scene.add(cube);
    const edgesGeometry = new THREE.EdgesGeometry(geometry);
    const lines = new THREE.LineSegments(edgesGeometry, new THREE.LineBasicMaterial({color: 0x000000}));
    cube.add(lines);

    const mouseNDRCoordinates = new THREE.Vector2();
    function onMouseMove(event) {
        // calculate mouse position in normalized device coordinates
        // (-1 to +1) for both components
        mouseNDRCoordinates.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouseNDRCoordinates.y = -(event.clientY / window.innerHeight) * 2 + 1;
    }
    window.addEventListener('mousemove', onMouseMove, false);

    const raycaster = new THREE.Raycaster();
    let myText = new Text();
    function writePositionText() {
        // update the picking ray with the camera and mouse position
        raycaster.setFromCamera(mouseNDRCoordinates, camera);

        // calculate objects intersecting the picking ray
        const intersects = raycaster.intersectObjects(scene.children);

        if (intersects.length > 0) {
            for (let i = 0; i < intersects.length; i++) {
                intersects[i].object.material.color.set(0xff0000);

                let interSectionPoint = "x: " + intersects[i].point.x + ", y:" + intersects[i].point.y + ", z: " + intersects[i].point.z;

                // Set properties to configure:
                myText.text = interSectionPoint;
                myText.fontSize = 0.4;
                myText.position.x = -3.7;
                myText.position.y = 2.5;
                myText.color = 0x0000FF;

                // Update the rendering:
                myText.sync();
                scene.add(myText);
            }
        }
    };

    function animate() {
        writePositionText();

        requestAnimationFrame(animate);
        renderer.render(scene, camera);
    }

    animate();

</script>
</body>
</html>

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.