Hey, I got basic raycasting to work, changing the color of my mesh when I mouse over it, but I don’t know how to change the color back to the original once the pointer stops intersecting with the mesh
//////////////////////////////////////////////////////////////////////////////////////////
import * as THREE from 'three';
//////////////////////////////////////////////////////////////////////////////////////////
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setAnimationLoop( animate );
document.body.appendChild( renderer.domElement );
//////////////////////////////////////////////////////////////////////////////////////////
const geometry = new THREE.BoxGeometry( 1, 1, 1 );
const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
const cube = new THREE.Mesh( geometry, material );
scene.add( cube );
//////////////////////////////////////////////////////////////////////////////////////////
camera.position.z = 5;
//////////////////////////////////////////////////////////////////////////////////////////
function animate() {
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
}
//////////////////////////////////////////////////////////////////////////////////////////
function render() {
renderer.render( scene, camera );
}
//////////////////////////////////////////////////////////////////////////////////////////
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function onPointerMove( event ) {
// calculate pointer position in normalized device coordinates
// (-1 to +1) for both components
pointer.x = ( event.clientX / window.innerWidth ) * 2 - 1;
pointer.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
// update the picking ray with the camera and pointer position
raycaster.setFromCamera( pointer, camera );
// calculate objects intersecting the picking ray
const intersects = raycaster.intersectObjects( scene.children, true );
const color = new THREE.Color( 1, 0, 0 );
intersects[ 0 ].object.material.color.set( color );
}
//////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener( 'pointermove', onPointerMove );
window.requestAnimationFrame( render );
//////////////////////////////////////////////////////////////////////////////////////////