Three.JS: New Colour at 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>
    const scene = new THREE.Scene();

    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    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);
    cube.position.y = -2;
    scene.add(cube);

    const mouseCoordinates = new THREE.Vector2();
    function onMouseMove( event ) {
        // calculate mouse position in normalized device coordinates
        // (-1 to +1) for both components

        mouseCoordinates.x = ( event.clientX / window.innerWidth ) * 2 - 1;
        mouseCoordinates.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
    }
    window.addEventListener( 'mousemove', onMouseMove, false );

    const raycaster = new THREE.Raycaster();
    function animate() {
        // update the picking ray with the camera and mouse position
        raycaster.setFromCamera( mouseCoordinates, camera );

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

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

        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.